在 React 中,受控组件和非受控组件是两种处理表单元素的方式,它们涉及到 React 组件如何处理和维护表单元素的状态。
<input>
<textarea>
<select>
示例:
class ControlledComponent extends React.Component { constructor(props) { super(props); this.state = { inputValue: '' }; } handleChange = (event) => { this.setState({ inputValue: event.target.value }); }; render() { return ( <input type="text" value={this.state.inputValue} onChange={this.handleChange} /> ); } }
class UncontrolledComponent extends React.Component { inputRef = React.createRef(); handleSubmit = (event) => { event.preventDefault(); alert(`Input Value: ${this.inputRef.current.value}`); }; render() { return ( <form onSubmit={this.handleSubmit}> <input type="text" ref={this.inputRef} /> <button type="submit">Submit</button> </form> ); } }
原文链接:codingdict.net