Babel 转译器 这是react自带的一个编译器
props和states一个是组件外部的,一个是组件内部的
jsx代表objects.
Hello.js
import React from ‘react‘; export default ({ name }) => <h1>Hello {name}!</h1>;
index.html
<div id="root"></div>
index.js
import React, { Component } from ‘react‘; import { render } from ‘react-dom‘; import Hello from ‘./Hello‘; import ‘./style.css‘; import Name from ‘./Name‘; class App extends Component { constructor() { super(); this.state = { name: ‘React1‘, insertName: ‘xss‘, hasNameFlag :true }; } changeName = () => { this.setState({ insertName: ‘yys‘, }) } deleteName = () =>{ this.setState({ hasNameFlag :false }) } render() { const { insertName,hasNameFlag} = this.state; const a = ( <h1 className={"greeting"} title="yys"> Hello, world! </h1> ); let name = null; if(hasNameFlag){ name = <Name name={insertName} />; } return ( <div> <Hello name={this.state.name} /> {name} <button onClick={this.changeName}>改名</button> <button onClick={this.deleteName}>删除</button> <p> Start editing to see some magic happen :) </p> </div> ); } } render(<App />, document.getElementById(‘root‘));
Name.js
import React, { Component } from ‘react‘; class Name extends Component { constructor(props) { super(props); this.state = { name: props.name }; } componentWillReceiveProps(nextProps){ if(nextProps.name === this.props.name) return; this.setState({ name:nextProps.name }) } componentDidUpdate(){ console.log("componentDidUpdate"); } componentWillUnmount(){ console.log("componentWillUnmount"); } render() { const { name } = this.state; return <h2>{name}</h2> } } export default Name;
constructor 1 只执行一次
compomentwillMount 1 dom放进去之前,也是只执行一次
componentDidMount 1 dom放进去之后,也是只执行一次
componentwillReceIveProps 有改变就执行,修改states的时候用到
componentwillupDate dom更新之前
componentDidupDate dom更新之后
componentWillUnmount dom组件被移除之前被调用,可以用于做一些清理工作