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: "" };
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。