Mar*_*ane 5 javascript reactjs
我按照教程使用react.js 发布了这个https://jsbin.com/foxoxejilu/1/edit?js,output.
我对道具和国家感到困惑.在save方法中Note component,这条线做了什么
this.props.onChange(this.refs.newText.value, this.props.id)
Run Code Online (Sandbox Code Playgroud)
而且我没有在代码中的其他地方看到onChange和onRemove函数,是一个预构建函数的反应吗?如何反应知道DOM被更改或删除?
我们可以总结一下这样的事情:
一个Parent(Board)打包她的Child(Note)一个包(props)并放一个手机(onChange)并说:如果你想告诉我一些事情,只需给我留言.然后一段时间后,孩子认为"让我的父母发短信",以便儿童将电话从他的财产中取出,然后给父母发短信:this.props.onChange("Thank you for sandwiches").然后,Parent接收消息并将其保存到她的笔记本中(state):this.setState({notes})
这是孩子收到属性(道具)的地方:
<Note key={note.id}
id={note.id}
onChange={this.update}
onRemove={this.remove}>
{note.note}
</Note>
Run Code Online (Sandbox Code Playgroud)
当上面的render()方法找到Board组件的方法时(通过{this.state.notes.map(this.eachNote)},就像Board说,
Note组件,让它给它一些属性(道具)".onChange,当它被Note后者调用时,让我们执行我自己的方法update"onChange我们就可以把它称为任何我们想要的东西<Note ... fromParentWithLove={this.update}> ... </Note>,但是让我们称它为onChange更容易遵循我们的意图."然后,我们可以移动到子组件 - Note.Note对自己说:
save方法:"<button onClick={this.save}>Save</button>save方法中,让我们调用onChange父母Board通过道具给我的功能":this.props.onChange(this.refs.newText.value, this.props.id)"作为参考,下面是从JSBin复制的代码:
var Note = React.createClass({
getInitialState(){
return {editing: false}
},
edit() {
this.setState({editing: true})
},
save() {
this.props.onChange(this.refs.newText.value, this.props.id)
this.setState({editing: false})
},
remove() {
this.props.onRemove(this.props.id)
},
renderForm() {
return(
<div className="note">
<textarea ref="newText"></textarea>
<button onClick={this.save}>Save</button>
</div>
)
},
renderDisplay() {
return(
<div className="note">
<p>{this.props.children}</p>
<span>
<button onClick={this.edit}>Edit</button>
<button onClick={this.remove}>X</button>
</span>
</div>
)
},
render() {
return (this.state.editing) ? this.renderForm() : this.renderDisplay()
}
})
var Board = React.createClass({
propTypes: {
count: function(props, propName) {
if(typeof props[propName] !== 'number'){
return new Error('the count must be a number')
}
}
},
getInitialState() {
return {
notes: [
{id:1, note:'Call boook'},
{id:2, note:'Buy Something'},
{id:3, note:'Wash Clothes'},
{id:4, note:'Go Jogging'}
]
}
},
update(newText, id){
var notes = this.state.notes.map(
note => (note.id !== id) ?
note:
{
...note,
note:newText
}
)
this.setState({notes})
},
remove(id){
var notes = this.state.notes.filter(note => note.id !== id)
this.setState({notes})
},
eachNote(note) {
return (<Note key={note.id}
id={note.id}
onChange={this.update}
onRemove={this.remove}>
{note.note}
</Note>)
},
render() {
return (<div className='board'>
{this.state.notes.map(this.eachNote)}
</div>)
}
})
ReactDOM.render(<Board count={10}> </Board>,
document.getElementById('react-container'))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
488 次 |
| 最近记录: |