今天講三種component的建立方式,也是看網路上的Demo常用的,我這邊會寫三個一樣的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放在這邊!
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
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囉,三個寫下來也讓我更清楚了!
參考資料: