1. 程式人生 > >React基礎篇-元件;props;state

React基礎篇-元件;props;state

1.定義元件

//方法一:類似於建構函式的方式
    function Welcome(props) {
        return <h1>Hello, {props.name}</h1>;
    }
    
//方法二:ES6中類的方式
    class Welcome extends React.Component {
        render() {
            return <h1>Hello, {this.props.name}</h1>;
        }
    }

    ReactDOM.render(
        <Welcome name="Tom"/>,
        document.getElementById("app")
    )

2.元件渲染

function Welcome(props) {
    return <h1>Hello, {props.name}</h1>;
}
const element = <Welcome name="Tom" />;
ReactDOM.render(
    element,
    document.getElementById('app')
);
——————————————————————————————————————————————————————————————————————————————————————————
分析過程:
    1.我們對<Welcome name="Tom" />元素呼叫了ReactDOM.render()方法。
    2.React將{name: 'Tom'}作為props傳入並呼叫Welcome元件。
    3.Welcome元件將<h1>Hello, Tom</h1>元素作為結果返回。
    4.React DOM將DOM更新為<h1>Hello, Tom</h1>。

3.元件注意

1、元件定義的名稱需以大寫開頭,區分函式定義;

2、React元素在何種方法中,均需以return返回;

3、元件的返回只允許有一個根元素;

4、提取元件時需注意,儘量提取複用性多的元件,哪怕只是一個按鈕,表單,表格等;

5、元件是真正隔離的,同一個元件不同引用不互相影響;

4.props(只讀性)

無論是使用函式或者類來宣告一個元件,它決不能修改它自己的props

5.state(狀態)

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);
——————————————————————————————————————————————————————————————————————————————————————————
注意:
    1.在 render() 方法中使用 this.state.date 替代 this.props.date;
    2.新增一個類建構函式來初始化狀態 this.state;
    3.在類建構函式中使用 props 永遠呼叫基礎建構函式;
    4.每次state變更,就會重新渲染,但只是重渲染改變的部分;
    5.如需更改state,需使用 this.setState({date:new Date()}),切不可直接更新;
    6.constructor建構函式是this.state初始化唯一的地方;