Day14, React components 各種寫Component的方法

這系列的文章主要備份自it鐵人賽: http://ithelp.ithome.com.tw/users/20103835/articles

今天講三種component的建立方式,也是看網路上的Demo常用的,我這邊會寫三個一樣的Component,讓大家看看彼此間的互換。

最簡單的 extends React.Component 開始

import React, { PropTypes } from 'react';
const  propTypes = {
updateName: PropTypes.func.isRequired,
name: PropTypes.string.isRequired,
};
class HelloWorldComponentWidget extends React.Component {
constructor(props){
super(props);
}

handleChange(e) {
const name = e.target.value;
this.props.updateName(name);
}
  render() {
const { name } = this.props;
return (
<div className="container">
<h3>
Hello, {name}!
</h3>
<hr />
<form className="form-horizontal">
<label>
Say hello to:
</label>
<input
type="text"
value={name}
onChange={e => this.handleChange(e)}
/>
</form>
</div>
);
}
}
HelloWorldComponentWidget.propTypes = propTypes;
export default HelloWorldComponentWidget;

來,以這個為基準,去改成另外兩個。
一定要Constructor,然後要把state的初始化放在constructor,最好也把function bind this放在這邊!

再來是不用this的createClass

import React, { PropTypes } from 'react';
const HelloWorldClassWidget = React.createClass({
propTypes: {
updateName: PropTypes.func.isRequired,
name: PropTypes.string.isRequired,
},
handleChange: function(e) {
const name = e.target.value;
this.props.updateName(name);
},
render() {
const { name } = this.props;
return (
<div className="container">
<h3>
Hello, {name}!
</h3>
<hr />
<form className="form-horizontal">
<label>
Say hello to:
</label>
<input
type="text"
value={name}
onChange={this.handleChange}
/>
</form>
</div>
);
}
});
export default HelloWorldClassWidget;

你看看onChange={this.handleChange},他不用bind this,就是裡面的function都會自己bind this,除此之外就是一些getDefaultProps 跟 extend React.Component中的 defaultProps的替換,然後要用getInitialState()去預設state

最後是我很少用的stateless component

import React, { PropTypes } from 'react';
const propTypes = {
updateName: PropTypes.func.isRequired,
name: PropTypes.string.isRequired,
};
const HelloWorldStatelessWidget = (props) =>{
let handleChange = (e) => {
const name = e.target.value;
props.updateName(name);
};
const { name } = props;
return (
<div className="container">
<h3>
Hello, {name}!
</h3>
<hr />
<form className="form-horizontal">
<label>
Say hello to:
</label>
<input
type="text"
value={name}
onChange={handleChange}
/>
</form>
</div>
);
}
HelloWorldStatelessWidget.propTypes = propTypes;
export default HelloWorldStatelessWidget;

要轉到stateless component就不能使用state、ref,他也沒有LifeCycle的function可以用,據說他Performance比較好一些~其他的,你就把它當成一個function在寫,所以要宣告function,宣告變數都可以,但是最後要return一個jsx!

去細細品嚐這三個component,其實也很有意思的。
OK囉,三個寫下來也讓我更清楚了!
參考資料:

  1. https://toddmotto.com/react-create-class-versus-component/
  2. https://toddmotto.com/stateless-react-components/
  3. https://medium.com/@housecor/react-stateless-functional-components-nine-wins-you-might-have-overlooked-997b0d933dbc#.qca0emr2w
  4. http://jaketrent.com/post/react-stateless-components-missing/
Show your support

Clapping shows how much you appreciated 睏寶’s story.