React雙向數據綁定:model改變影響view,view改變反過來影響modelreact
import React,{Component} from 'react'; class Todolist extends Component { constructor(props) { super(props); this.state = { username:"111" }; } inputChange=(e)=>{ this.setState({ username:e.target.value }) } setUsername=()=>{ this.setState({ username:'李四' }) } render() { return ( <div> <h2>雙休數據綁定</h2><input value={this.state.username} onChange={this.inputChange}/> <p> {this.state.username}</p> <button onClick={this.setUsername}>改變username的值</button> </div> ); } } export default Todolist;
使用 map 渲染列表數據this
JSX 的表達式插入 {}
裏面能夠聽任何數據spa
用戶數據的 JSX 結構抽離成一個組件 User
,而且經過 props
把 user
數據做爲組件的配置參數傳進去;這樣改寫 Index
就很是清晰了,看一眼就知道負責渲染 users
列表,而用的組件是 User
code
const users = [
{ username: 'Jerry', age: 21, gender: 'male' },
{ username: 'Tomy', age: 22, gender: 'male' },
{ username: 'Lily', age: 19, gender: 'female' },
{ username: 'Lucy', age: 20, gender: 'female' }
]
class User extends Component {
render () {
const { user } = this.props
return (
<div>
<div>姓名:{user.username}</div>
<div>年齡:{user.age}</div>
<div>性別:{user.gender}</div>
<hr />
</div>
)
}
}
class Index extends Component {
render () {
return (
<div>
{users.map((user, i) => <User key={i} user={user} />)}</div>
)
}
}
ReactDOM.render(
<Index />,
document.getElementById('root')
)