gpt4 book ai didi

javascript - 使用 ReactJs 访问元素的输入值

转载 作者:行者123 更新时间:2023-12-02 14:59:06 25 4
gpt4 key购买 nike

如何检查输入字段是否包含来自另一个元素的任何值。我的尝试,

<div className='input-item'>
<input ref="accessKey" name="username" className="lci-text" type="text"/>

<label className={"helpers" + ((this.ref.accessKey.value.length > 0) ? 'toggled' : '')}>Access Key</label>
</div>

当输入有任何值时,我尝试将类“.toggled”添加到标签,但在控制台中出现以下错误。

Uncaught TypeError: Cannot read property 'accessKey' of undefined

更新

我也尝试过 this.refs.accessKey.value.length 这次出现以下错误

Uncaught TypeError: Cannot read property 'value' of undefined

请帮我解决这个问题。

最佳答案

不建议直接访问 ref 来对同一组件进行更改。此外,由于您使用的是 React,因此需要使用 this.state

作为旁注,您应该使用 npm package classNames

下面是使用 React State 更新的代码。

HTML

<div id="container"></div>

CSS

.helpers{ color: red }
.helpers.toggled{ color: green }

Javascript

var Hello = React.createClass({

getInitialState: function() {
return {value: ''};
},

handleChange: function(event) {
this.setState({value: event.target.value});
},

render: function() {
var toggled = this.state.value.length ? ' toggled' : '';

return (
<div>
<input type='text'
value={ this.state.value }
onChange={ this.handleChange }
/>
<label className={ 'helpers' + toggled }>Access Key</label>
</div>
);
}

});

ReactDOM.render(
<Hello />,
document.getElementById('container')
);

fiddle

https://jsfiddle.net/qejxjo1x/2/

<小时/>

Official Notes and References :

  • Never access refs inside of any component's render method – or while any component's render method is even running anywhere in the call stack.

  • If you want to preserve Google Closure Compiler advanced-mode crushing resilience, make sure to never access as a property what was specified as a string. This means you must access using this.refs['myRefString'] if your ref was defined as ref="myRefString".

  • If you have not programmed several apps with React, your first inclination is usually going to be to try to use refs to "make things happen" in your app. If this is the case, take a moment and think more critically about where state should be owned in the component hierarchy. Often, it becomes clear that the proper place to "own" that state is at a higher level in the hierarchy. Placing the state there often eliminates any desire to use refs to "make things happen" – instead, the data flow will usually accomplish your goal.

关于javascript - 使用 ReactJs 访问元素的输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35577946/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com