一:创建react项目
cnpm install -g create-react-app // 全局安装构建react项目的工具
create-react-app xxx // 用工具创建名为xxx的react项目
cd my-app && npm start // 进入项目并运行
二:react元素渲染
根元素: <div id="example"></div>
创建对象: const element = <h1>Hello, world!</h1>
渲染: ReactDOM.render( element, document.getElementById('example') )
三: 封装组件
封装组件的两种方法:
直接用一个function方法: function HelloMessage(props) { return <h1>Hello World!</h1>; }
使用 ES6 class 来定义一个组件:
class Welcome extends React.Component {
render() {
return <h1>Hello World!</h1>;
}
}
四: React State(状态)
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
tick() {
this.setState({
date: new Date()
});
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>现在是 {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
ReactDOM.render(
<Clock />,
document.getElementById('example')
);
// 在class中调用state需要用this.state调用
// 改变state中的属性需要使用
this.setState({
xxx属性名: xxx对象
});
或:
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
})); // 将之前状态state传为参数
五: React Props
state 和 props 主要的区别在于 props 是不可变的,而 state 可以根据与用户交互来改变。这就是为什么有些容器组件需要定义 state 来更新和修改数据。 而子组件只能通过 props 来传递数据。对应vue中自己的变量和父组件传过来的变量
可以设置默认props,选定类型,是否必填:
HelloMessage.defaultProps = { name: 'Runoob' };
六: React事件处理
写法: <button onClick={activateLasers}>激活按钮</button>
绑定方法中解决this的指向问题的三种方法:
第一: 在constructor构造方法中加入this.handleClick = this.handleClick.bind(this); // 利用bind方法将方法中的this指向为全局
第二: handleClick = () => { console.log('this is:', this); } // 利用es6中的函数写法可以避免this的指向问题
第三: 在绑定时直接使用es6箭头函数<button onClick={(e) => this.handleClick(e)}> Click me </button>不建议使用
事件传参:
<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button> 或 <button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>
deleteRow(name, e){ //事件对象e要放在最后 e.preventDefault(); alert(name); }
七: React条件渲染
可以用if或&&或三目运算符
阻止条件渲染可以在方法中直接判断条件后返回null
八: React列表 & Keys
利用js的map方法或forEach
九: React组件API
设置状态:setState : setState(object nextState[, function callback])
nextState,将要设置的新状态,该状态会和当前的state合并
callback,可选参数,回调函数。该函数会在setState设置成功,且组件重新渲染后调用。
替换状态:replaceState :replaceState(object nextState[, function callback])
nextState,将要设置的新状态,该状态会替换当前的state。
callback,可选参数,回调函数。该函数会在replaceState设置成功,且组件重新渲染后调用。
注:replaceState()方法与setState()类似,但是方法只会保留nextState中状态,原state不在nextState中的状态都会被删除。
设置属性:setProps:setProps(object nextProps[, function callback])
nextProps,将要设置的新属性,该状态会和当前的props合并
callback,可选参数,回调函数。该函数会在setProps设置成功,且组件重新渲染后调用。
替换属性:replaceProps: replaceProps(object nextProps[, function callback])
nextProps,将要设置的新属性,该属性会替换当前的props。
callback,可选参数,回调函数。该函数会在replaceProps设置成功,且组件重新渲染后调用。
注: replaceProps()方法与setProps类似,但它会删除原有 props。
强制更新:forceUpdate: forceUpdate([function callback])
callback,可选参数,回调函数。该函数会在组件render()方法调用后调用。
获取DOM节点:findDOMNode: DOMElement findDOMNode()
如果组件已经挂载到DOM中,该方法返回对应的本地浏览器 DOM 元素。当render返回null 或 false时,this.findDOMNode()也会返回null。从DOM 中读取值的时候,该方法很有用,如:获取表单字段的值和做一些 DOM 操作。
判断组件挂载状态:isMounted: bool isMounted()
isMounted()方法用于判断组件是否已挂载到DOM中。可以使用该方法保证了setState()和forceUpdate()在异步场景下的调用不会出错。
十: React组件生命周期
组件的生命周期可分为3个状态:
- Mounting:已插入真实 DOM
- Updating:正在被重新渲染
- Unmounting:已移出真实 DOM
生命周期的方法:
componentWillMount() :在渲染前调用,在客户端也在服务端。
componentDidMount(): 在第一次渲染后调用,只在客户端。之后组件已经生成了对应的DOM结构,可以通过this.getDOMNode()来进行访问。 如果你想和其他JavaScript框架一起使用,可以在这个方法中调用setTimeout, setInterval或者发送AJAX请求等操作(防止异步操作阻塞UI)。
componentWillReceiveProps(newProps): 在组件接收到一个新的 prop (更新后)时被调用。这个方法在初始化render时不会被调用。
shouldComponentUpdate(newProps, newState): 返回一个布尔值。在组件接收到新的props或者state时被调用。在初始化时或者使用forceUpdate时不被调用。可以在你确认不需要更新组件时使用。
componentWillUpdate(nextProps, nextState): 在组件接收到新的props或者state但还没有render时被调用。在初始化时不会被调用。
componentDidUpdate(prevProps, prevState): 在组件完成更新后立即调用。在初始化时不会被调用。
componentWillUnmount(): 在组件从 DOM 中移除之前立刻被调用。
十一: React 表单与事件
双向绑定: <input type="text" value={this.props.myDataProp} onChange={this.props.updateStateProp} />
多个表单: 当你有处理多个 input 元素时,你可以通过给每个元素添加一个 name 属性,来让处理函数根据 event.target.name 的值来选择做什么。但是name属性值需要和绑定的数据一一对应: const name = event.target.name; this.setState({ [name]: value });
子组件修改父组件的属性: 可以利用props将父组件的方法传给子组件调用
十二: React Refs
使用方法: <input ref="myInput" />
var input = this.refs.myInput; // 获得这个对象的html对象 var inputValue = input.value; var inputRect = input.getBoundingClientRect(); // 获得这个对象的react实例