react学习笔记(二)组件、props和state

组件、props和state

组件

React组件分为function组件和class组件,都以大写字母开头,都是自定义组件,且这两种组件是等价的。class组件需要使用ES6 class创建一个class,然后继承React.Component,添加一个render()方法,在方法中返回jsx格式的模板字符串。

Note: Always start component names with a capital letter.
React treats components starting with lowercase letters as DOM tags. For example,

represents an HTML div tag, but represents a component and requires Welcome to be in scope.

在React中,使用自定义组件必须以大写字母开头,而小写字母开头的组件则是html标签。

// function组件
function Print() {
	return <div>hello world</div>
}
// class组件
class Print extends React.Component {
	render() {
		return <div>hello world</div>
	}
}

props

When React sees an element representing a user-defined component, it passes JSX attributes to this component as a single object. We call this object “props”

父组件传递给子组件的单一对象就是props,且props的值是只读的,不可修改。

state

state和props类似,它们的值都是异步更新的,然state属于组件私有的,可以任意更改值。

异步更新

在组件中可以多次重复的设置state的值,这些操作是异步的,故在更新一个state的属性时,不能使用其现有的值。

// 错误的方式
this.setState({
	count: this.state.count + this.props.add
})
// 正确的方式,preState和preProps是staet和props改变之前的值
this.setState((preState, preProps) => {
	count: preState.count + props.add
})

总结

  1. 自定义组件都以大写字母开头
  2. props是只读的
  3. setState()方法是异步的

猜你喜欢

转载自blog.csdn.net/harmsworth2016/article/details/85784502