在本章中,我們將學(xué)習(xí)如何在React中使用表單。
在以下示例中,我們將使用設(shè)置輸入表單value = {this.state.data}。只要輸入值發(fā)生變化,就可以更新狀態(tài)。我們正在使用onChange事件,它將監(jiān)視輸入更改并相應(yīng)地更新狀態(tài)。
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;import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App/>, document.getElementById('app'));當(dāng)輸入文本值更改時(shí),狀態(tài)將被更新。

在下面的示例中,我們將看到如何使用子組件中的表單。onChange方法將觸發(fā)狀態(tài)更新,該狀態(tài)更新將傳遞到子輸入value并呈現(xiàn)在屏幕上。事件一章中使用了類似的示例。每當(dāng)我們需要從子組件更新狀態(tài)時(shí),我們都需要將處理update(updateState)的函數(shù)作為prop(updateStateProp)傳遞。
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;import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App/>, document.getElementById('app'));這將產(chǎn)生以下結(jié)果。
