1. 程式人生 > >React建立元件的三種方式

React建立元件的三種方式

無狀態函式式元件

建立無狀態函式式元件形式是從React 0.14版本開始出現的。它是為了建立純展示元件,這種元件只負責根據傳入的props來展示,不涉及到要state狀態的操作。

function HelloComponent(props, /* context */) {
  return <div>Hello {props.name}</div>
}
ReactDOM.render(<HelloComponent name="Sebastian" />, mountNode) 

Es6箭頭函式寫法
const FindComponent=()=> {
  return <div>OH!</div>
}
一定要注意使用var let const 來宣告否則無用

React.createClass

`React.createClass`是react剛開始推薦的建立元件的方式,這是ES5的原生的JavaScript來實現的React元件

但現在基本不用React也會慢慢將其淘汰

React.Component

React.Component是以ES6的形式來建立react的元件的,是React目前極為推薦的建立有狀態元件的方式,最終會取代React.createClass形式;相對於 React.createClass可以更好實現程式碼複用。將上面React.createClass的形式改為
React.Component形式如下:
class InputControlES6 extends React.Component {
    constructor(props) {
        super(props);

        // 設定 initial state
        this.state = {
            text: props.initialValue || 'placeholder'
        };

        // ES6 類中函式必須手動繫結
        this.handleChange = this.handleChange.bind(this);
    }

    handleChange(event) {
        this.setState({
            text: event.target.value
        });
    }

    render() {
        return (
            <div>
                Type something:
                <input onChange={this.handleChange}
               value={this.state.text} />
            </div>
        );
    }
}
InputControlES6.propTypes = {
    initialValue: React.PropTypes.string
};
InputControlES6.defaultProps = {
    initialValue: ''
};