1. 实现效果

input输入框显示的是state中的数据,state改变,input输入框中的值也跟着改变:

手动更改输入框的值,state也会相应改变:

2. 实现过程

使用 React-Hook,首先定义渲染input输入框值的state,初始值为空:

const [inputValue, setInputValue] = useState('');

然后在input输入框中添加value属性,属性值为inputValue,由inputValue决定显示的内容。

<input type="text" className="inputDemo" value={inputValue} />

然而浏览器会报出警告,意思是给input添加了value属性,必须再加上onChange 或者readOnly属性,要么就将 value 改为defaultValue

Warning: You provided a value prop to a form field without an onChange handler. This will render a read-only field. If the field should be mutable use defaultValue. Otherwise, set either onChange or readOnly.

要实时显示inputValue的内容,当然不能设置为defaultValue,也不能设置只读readOnly,所以加上onChange事件,里面定义一个函数,功能为根据inputvalue改变状态:

<input
	type="text"
	className="inputDemo"
	value={inputValue}
	onChange={e => {
		setInputValue(e.target.value);
	}}
/>

onChange里面的函数,接受事件对象为参数,通过事件对象,可以拿到当前的value

3. 完整代码

import { useState } from 'react';
import './index.css';

const Demo = () => {
    const [inputValue, setInputValue] = useState('');
    return (
        <>
            <input
                type="text"
                className="inputDemo"
                value={inputValue}
                onChange={e => {
                    setInputValue(e.target.value);
                }}
            />
        </>
    );
};

export default Demo;

📘📘欢迎在我的博客上访问:
https://lzxjack.top/

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐