@duanyubin
2015-06-04T08:39:39.000000Z
字数 2547
阅读 397
javascript
key
to dynamic Children
var Wrapper = React.createClass({
render: function(){
var className = "inner"
return (
<div>
This is Wrapper
<Inner className={className} />
</div>
)
}
})
var Inner = React.createClass({
render: function(){
return (
<div className={this.props.className}>
This is inner, className is {this.props.className}
</div>
)
}
})
React.render(<Wrapper />, document.body);
props
-- <div className={}>
state
-- Things that will change you simply update a component's state, and then render a new UI based on this new state.
Simply ask three questions about each piece of data:
1. Does it change over time? If not, it probably isn't state. (在某一时间点改变值)
2. Is it passed in from a parent via props? If so, it probably isn't state.(不来自于父元素)
3. Can you compute it based on any other state or props in your component? If so, it's not state.(不能由其他值计算得出)
Question: If a value passed in from a parent via props, but it will change in some time, is this state?
Mount -> Update -> Unmount
Invoked once before the component is mounted. The return value will be used as the initial value of this.state.
Mounting: componentDidMount
Integrate with other JavaScript frameworks, set timers using setTimeout or setInterval, or send AJAX requests
Updating: componentWillUpdate
clear timeout, clean DOM events
key
to dynamic Children
...
render: function(){
var list = this.props.list
return (
<div>
{
list.map(function(item){
return <Other item={item} key={item.id} />
})
}
</div>
)
}
...
Bind in componentDidMount
method and unbind in componentWillUnmount
...
render: function(){
var className = "aa"
if(..) className += ' bb'
return <div className={className} />
}
...
For child-parent communication
var GroceryList = React.createClass({
handleClick: function(i) {
console.log('You clicked: ' + this.props.items[i]);
},
render: function() {
return (
<div>
{this.props.items.map(function(item) {
return (
<div onClick={this.handleClick.bind(this, i)} key={item}>{item}</div>
);
}, this)}
</div>
);
}
});
React.render(
<GroceryList items={['Apple', 'Banana', 'Cranberry']} />, mountNode
);
For communication between two components that don't have a parent-child relationship
Use your own event system
In JSX, always return one element
render: function(){
return (
<article />
<article />
)
}
render: function(){
return (
<section>
<article />
<article />
</section>
)
}