[英]Is value attribute of input tag a part of DOM?
I have some default value, that should be passed to value attribute of input, so this will be controlled component. 我有一些默认值,应该将其传递给输入的value属性,因此这将是受控组件。 What I need to know, where I should initialize state, in
constructor
enter code here or componentDidMount
? 我需要知道的是,我应该在哪里
constructor
状态,在constructor
在此处输入代码或componentDidMount
? I find, that componentDidMount
is the right place for initialization that requires DOM nodes. 我发现,
componentDidMount
是需要DOM节点进行初始化的正确位置。 So that's why I ask about value attribute. 所以这就是为什么我问值属性。
as you said componentDidMount
is the right place for initialization but exactly for the requirement that needs DOM node's measurements like width or height in browser after render (here you can use element's width for some purpose). 正如您所说的,
componentDidMount
是初始化的正确位置, 但恰好满足渲染后需要DOM节点的度量值(例如浏览器中浏览器的宽度或高度)的要求(此处您可以出于某些目的使用元素的宽度)。
so in your case (i mean input ), there is no need to set value in componentDidMount
. 因此,在您的情况下(我的意思是input ),无需在
componentDidMount
设置值。
hence you can simply use constructor that's enough. 因此,您只需使用足够的构造函数即可。
Hope this helps. 希望这可以帮助。
Use ref
to get value of <input/>
, update state
and initialize this.inputRef.current.value
. 使用
ref
获取<input/>
值,更新state
并初始化this.inputRef.current.value
。 This is working solution of question, 这是问题的可行解决方案,
class App extends React.Component{ constructor(props){ super(props); this.inputRef = React.createRef(); this.state = { inputValue: 'This is App component' } } componentDidMount(){ this.inputRef.current.value = this.state.inputValue; } keypressHandler = (event) => { if(event.key === 'Enter') this.setState({inputValue: this.inputRef.current.value}); } render() { return ( <div> <label>Type text and press enter</label><br/> <input type='text' ref={this.inputRef} onKeyPress={(event) => this.keypressHandler(event)}/> <p>{this.state.inputValue}</p> </div> ); } } ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id='root' />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.