gpt4 book ai didi

javascript - ReactJs打印输入字段的值

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

我正在尝试立即打印渲染函数中的输入值。

concept of state and lifecycle 的文档中在 React 组件中,我看到使用了 constructorsuper(props) 以及 this.state

尝试相同时出现以下错误;

Uncaught TypeError: Cannot read property 'state' of undefined

下面是我的代码;

class App extends React.Component {
constructor(props) {
super(props);
this.state = {
text: ''
};
};

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

render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.text}.</h2>
<input type="text" onKeyUp={this.handleChange} />
</div>
);
}
}

如何修复它?

最佳答案

当你调用这样的函数时,它是由窗口调用的,而不是由你的 react 对象调用的。

为了使函数绑定(bind)到你的react对象(并且能够使用setState方法,你需要使用这个:

onKeyUp={this.handleChange.bind(this)}

this 会将其绑定(bind)到您的 react 对象:)

关于javascript - ReactJs打印输入字段的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40223934/

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