Open zbb opened 7 years ago
概念①: Component-Based
A component takes input data and returns what to display. Input data can be accessed by render() via (概念②) this.props.
class HelloMessage extends React.Component {
render() {
return <div>Hello {this.props.name}</div>;
}
}
ReactDOM.render(<HelloMessage name="Jane" />, mountNode);
概念③: this.state 和 prevState When a component's state data changes, the rendered markup will be updated by re-invoking render().
constructor(props) {
super(props);
this.state = {secondsElapsed: 0};
}
this.setState( () => ({
do something to state
}))
这个就是调用了父类的构造函数,因为我们知道react希望把所有props, state的定义尽量放到父类中进行,所以我们需要在子类中调用父类构造函数来使用这些值。 子类必须在constructor方法中调用super方法,否则新建实例时会报错。这是因为子类没有自己的this对象,而是继承父类的this对象,然后对其进行加工。如果不调用super方法,子类就得不到this对象。
es6的class: http://es6.ruanyifeng.com/#docs/class286
概念④: componentDidMount、 componentWillUnmount
必须要在 constructor
里面重新绑定事件?
class TodoApp extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.state = {items: [], text: ''};
}
blablabla
概念⑤: refs dangerouslySetInnerHTML
handleChange() {
this.setState({value: this.refs.textarea.value});
}
......
<textarea
onChange={this.handleChange}
ref="textarea"
defaultValue={this.state.value} />
<h3>Output</h3>
React is pretty flexible but it has a single strict rule: All React components must act like pure functions with respect to their props.
React 相当灵活但有一个严格的规则: 所有组件对于 props来说 必须是纯粹的函数。(props 在组件内只读)
【state和 props】
this.state 用【收藏】类按钮来理解。 这个状态不在dom属性上, 在组件内部维护已收藏或未收藏。
由于 this.props 和 this.state 都用于描述组件的特性,可能会产生混淆。一个简单的区分方法是,this.props 表示那些一旦定义,就不再改变的特性,而 this.state 是会随着用户互动而产生变化的特性。 props,在这里很常见的用法是传参,显然形参你改了也没用 而state这个属性就要好好把玩了,也说了,交互中很常见的状态
是否是从父级通过 props 传入的?如果是,可能不是 state 。 是否会随着时间改变?如果不是,可能不是 state 。 能根据组件中其它 state 数据或者 props 计算出来吗?如果是,就不是 state 。
learning