简体   繁体   English

是否可以选择在 React 中的受控组件中使用值作为输入

[英]Is it optional to use value for input in Controlled component in React

I was learning React and wanted to learn how to properly use forms.我正在学习 React 并想学习如何正确使用表单。 Then I found out that there is something called Controlled forms so I wrote this code:然后我发现有一种叫做 Controlled forms 的东西,所以我写了这段代码:

<input
  name='name'
  value={this.state.name}
  onChange={e => this.handleChange(e)}
/>

Is it optional to use "value" attribute since we already add the input data to state with onChange ?是否可以选择使用“value”属性,因为我们已经将输入数据添加到状态onChange Is it true that value is needed just to ensure that the input data is properly added to the state?是否真的需要值只是为了确保将输入数据正确添加到状态中? Just to be confident?就为了自信?

A controlled component can be set by state or props because you give it a value property.受控组件可以通过 state 或 props 设置,因为你给了它一个 value 属性。 If you do not provide an onChange to a controlled component then you cannot change it's value because the value property comes from state or props.如果您没有为受控组件提供 onChange ,那么您将无法更改它的值,因为value属性来自 state 或 props。

An uncontrolled component does not have a value property so it manages it's own value, when the user types something in a textbox then it'll show that text.不受控制的组件没有value属性,因此它管理自己的值,当用户在文本框中键入内容时,它将显示该文本。 You can add onChange to an uncontrolled component but you can't reset it (because it doesn't have a value property).您可以将 onChange 添加到不受控制的组件,但不能重置它(因为它没有 value 属性)。

 const App = () => { const [controlled, setControlled] = React.useState(''); const onChange = React.useCallback( e => setControlled(e.target.value), [] ); return ( <div> <div> <label> contolled (can also set value with uncontrolled) <input type="text" value={controlled} onChange={onChange} /> </label> </div> <div> <label> contolled but no onChange, just follows other inputs <input type="text" value={controlled} /> </label> </div> <div> <label> uncontrolled (can never set it's value) <input type="text" onChange={onChange} /> </label> </div> </div> ); }; ReactDOM.render(<App />, document.getElementById('root'));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="root"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM