在本章中,我们将学习如何在react中使用表单。
在下面的例子中,我们将设置一个值为{this.state.data}
的输入表单。 这允许每当输入值改变时更新状态。使用onchange
事件,将监听输入值的更改并相应地更新状态。
文件: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(e) {
this.setstate({data: e.target.value});
}
render() {
return (
<div>
<input type = "text" value = {this.state.data}
onchange = {this.updatestate} />
<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'));
当输入文本值改变时,状态将被更新。
在下面的例子中,我们将看到如何使用子组件的表单。 onchange
方法将触发状态更新,将会传递给子输入值并在屏幕上呈现。事件章节中使用了一个类似的例子。无论何时需要从子组件更新状态,都需要将处理更新的函数(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(e) {
this.setstate({data: e.target.value});
}
render() {
return (
<div>
<content mydataprop = {this.state.data}
updatestateprop = {this.updatestate}></content>
</div>
);
}
}
class content extends react.component {
render() {
return (
<div>
<input type = "text" value = {this.props.mydataprop}
onchange = {this.props.updatestateprop} />
<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'));
这将产生以下结果 -