Renders an <input>
element with internal state, that uses a callback function to pass its value to the parent component.
- Use object destructuring to set defaults for certain attributes of the
<input>
element. - Use the
React.setState()
hook to create thevalue
state variable and give it a value of equal to thedefaultValue
prop. - Use the
React.useEffect()
hook with a second parameter set to thevalue
state variable to call thecallback
function every timevalue
is updated. - Render an
<input>
element with the appropriate attributes and use the theonChange
event to upda thevalue
state variable.
代码实现
function ControlledInput({
callback,
type = 'text',
disabled = false,
readOnly = false,
defaultValue,
placeholder = ''
}) {
const [value, setValue] = React.useState(defaultValue);
React.useEffect(() => {
callback(value);
}, [value]);
return (
<input
defaultValue={defaultValue}
type={type}
disabled={disabled}
readOnly={readOnly}
placeholder={placeholder}
onChange={({ target: { value } }) => setValue(value)}
/>
);
}
使用样例
ReactDOM.render(
<ControlledInput
type="text"
placeholder="Insert some text here..."
callback={val => console.log(val)}
/>,
document.getElementById('root')
);