首页 > react es6 怎么设置默认的props 于 state

react es6 怎么设置默认的props 于 state

如何写
getDefaultProps
getInitialState

非<Hello name="1111" />这样设置props

class Hello extends React.Component {
  render() {
    return <div>Hello {this.props.name} - {this.state.n}</div>;
  }
}
ReactDOM.render(
  <Hello />,
  document.getElementById('container')
);

state在constructor方法里写

...
constructor(props) {
    this.state = {
        n: ...
    }
}

写default props有两种方法

//1 在组件内部的使用static
...
static defaultProps = {
    name: ...
}

//2 在组件外部

Hello.defaultProps = {
    name: ...
}

比较推荐用 initialState() 一个自定义方法返回一个 state 的初始值比较好。因为在实际的使用过程中组件有可能需要在 componentWillReceiveProps 的时候重置状态,两个地方都需要使用初始 state 这时候使用一个 this.initialState() 方法会方便一点。

另外 this.state 也可以直接在 class 中定义,如果在 constructor 中定义且是继承组件的话需要使用 super() 方法来初始化父类,可以省点代码→_→。

class Hello extends React.Component {
    static defaultProps = {
        name: ''
    };
    this.state = this.initialState();
           
    componentWillReceiveProps(nextProps) {
        if(this.props.name !== nextProps.name) {
            this.setState(this.initialState());
        }
    }
    
    initialState() {
        return {n: 100};
    }
    
    render() {
        return <div>Hello {this.props.name} - {this.state.n}</div>;
    }
}

https://babeljs.io/blog/2015/06/07/react-on-es6-plus 这里有详细的解答
中文 http://blog.mcbird.cn/2015/09/11/react-on-es6-plus/

【热门文章】
【热门文章】