gpt4 book ai didi

javascript - ReactJS onChange 函数

转载 作者:行者123 更新时间:2023-11-28 18:09:54 26 4
gpt4 key购买 nike

我的 onChange 函数哪里出了问题?我希望能够在文本框中输入内容,但重新编译时不断收到以下控制台错误:

**Uncaught TypeError: Cannot read property 'value' of undefined**

参见下面的代码:

var name = "";
export default React.createClass({

handleChange: function() {
this.props.onUserInput(
this.refs.name.value
)
},

render() {
return (
<div>
<div>{this.props.children}</div>
<Well style={style.well}>
<div style={style.userContent}>

<input style={style.userDetails}
id ="userName"
type="text"
onChange={this.handleChange()}
value ={name} />

<Button bsStyle="primary">Update</Button>
</div>
</Well>
</div>
);
}
});

最佳答案

删除()。,对于onChange,您必须将引用传递给函数

onChange={ this.handleChange } 

更新:

此外,在这种情况下,您不需要 refs,因为您可以像这样获取值

handleChange: function (event) {
this.props.onUserInput(
event.currentTarget.value
)
},

根据您的示例,我发现您使用了变量name,这是不好的做法,我认为在这种情况下您可以使用state,就像我的示例中

const App = React.createClass({
getInitialState: function () {
return {
value: ''
}
},

handleChange: function (event) {
this.setState({
value: event.currentTarget.value
}, () => { // arrow function, ES2015
console.log(this.state.value);
// call this.props.onUserInput(this.state.value)
});
},

render() {
return (
<input style={ {} }
id="userName"
type="text"
onChange={ this.handleChange }
value={ this.state.value }
/>
);
}
});

ReactDOM.render(<App />, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

关于javascript - ReactJS onChange 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41855206/

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