在本章中,我们将学习如何使用事件。
这是一个简单的事件例子,只使用一个组件。 我们只是添加onclick
事件,当按钮被点击,将触发updatestate
函数。
文件:app.jsx -
import react from 'react';
class app extends react.component {
constructor(props) {
super(props);
this.state = {
data: 'initial data...'
}
this.updatestate = this.updatestate.bind(this);
};
updatestate() {
this.setstate({data: 'data updated...'})
}
render() {
return (
<div>
<button onclick = {this.updatestate}>click</button>
<h4>{this.state.data}</h4>
</div>
);
}
}
export default app;
文件:main.js -
import react from 'react';
import reactdom from 'react-dom';
import app from './app.jsx';
reactdom.render(<app/>, document.getelementbyid('app'));
这将产生以下结果 -
当需要从其子组件中更新父组件的状态时,我们可以在父组件中创建一个事件处理程序(updatestate
),并将其作为prop(updatestateprop
)传递给子组件,在那里可以调用它。
文件:app.jsx -
import react from 'react';
class app extends react.component {
constructor(props) {
super(props);
this.state = {
data: 'initial data...'
}
this.updatestate = this.updatestate.bind(this);
};
updatestate() {
this.setstate({data: 'data updated from the child component...'})
}
render() {
return (
<div>
<content mydataprop = {this.state.data}
updatestateprop = {this.updatestate}></content>
</div>
);
}
}
class content extends react.component {
render() {
return (
<div>
<button onclick = {this.props.updatestateprop}>click</button>
<h3>{this.props.mydataprop}</h3>
</div>
);
}
}
export default app;
文件:main.js -
import react from 'react';
import reactdom from 'react-dom';
import app from './app.jsx';
reactdom.render(<app/>, document.getelementbyid('app'));
这将产生以下结果 -