在 React 组件中访问状态值
Accessing state values in React Component
我对 reactjs 有点陌生。在 React.createclass 元素中,您可以访问输入值或任何状态值,例如此
change: function(e) {
this.setState({author: e.target.value});
},
但是在React.component中这是不可能的,所以我怎样才能在React.component[=20=中完成类似的任务]
谢谢
如果你想像这样onChange={ this.change }
将方法传递给事件处理程序并使用ES2015
类,你必须自己为这些方法设置this
,因为例子
class App extends React.Component {
constructor() {
super();
this.state = { author: '' };
this.change = this.change.bind(this); // set this for change method
}
change(e) {
this.setState({ author: e.target.value });
}
render() {
return <input onChange={ this.change } value={ this.state.author } />
}
}
我对 reactjs 有点陌生。在 React.createclass 元素中,您可以访问输入值或任何状态值,例如此
change: function(e) {
this.setState({author: e.target.value});
},
但是在React.component中这是不可能的,所以我怎样才能在React.component[=20=中完成类似的任务]
谢谢
如果你想像这样onChange={ this.change }
将方法传递给事件处理程序并使用ES2015
类,你必须自己为这些方法设置this
,因为例子
class App extends React.Component {
constructor() {
super();
this.state = { author: '' };
this.change = this.change.bind(this); // set this for change method
}
change(e) {
this.setState({ author: e.target.value });
}
render() {
return <input onChange={ this.change } value={ this.state.author } />
}
}