2019-09-20
描述
渲染一个可以使用回调函数将值传递给父组件的 <input>
元素。
- 使用对象解构为
<input>
元素的特定属性设置默认值 - 渲染一个包含适当属性的
<input>
元素,在onChange
事件中使用callback
函数将输入框的值传递给父组件
实现
function UncontrolledInput({ callback, type = 'text', disabled = false, readOnly = false, placeholder = '' }) { return ( <input type={type} disabled={disabled} readOnly={readOnly} placeholder={placeholder} onChange={({ target: { value } }) => callback(value)} /> ); }
使用
ReactDOM.render( <UncontrolledInput type="text" placeholder="Insert some text here..." callback={val => console.log(val)} />, document.getElementById('root') );