函數式組件即是用函數的方式來聲明組件,其特點在於組件可以直接寫在頁面內無需再起一個新的頁面,同時只需要一個return(),不需要在組件中使用render()。
正常的組件都會在class(class MainTable extends React.Component {}
)中聲明,有render且需要return。
本篇將會講述兩種 函數式定義的組件。兩種方式,寫法略有不同,但是理念是一致的。
(一)函數是組件的特點
- 只需return
- 同一個頁面內聲明以及使用,即只需要一個文件。
- 組件中調用props相關的參數或函數時,都不能用
this.props.
,需替換成props.
(二)方式一:函數式聲明,函數式調用(可參照React中文社區)
(1)在class外聲明 組件
// 函數式組件,寫法1
// 注意,props需要傳入。
function SquareButton(props) {
return (
<button className="square" onClick={props.onClick}>
{props.value}
</button>
);
}
(2)在class內調用
// 函數式調用(這裏當做參數squares 函數handleClick都已經聲明好了。)
class MainTable extends React.Component {
renderSquare(i) {
return (
<Square
value={this.state.squares[i]}
onClick={() => this.handleClick(i)}
/>
);
}
// render中調用
render() {
return(
<div className="board-row">
{this.renderSquare(0)}
{this.renderSquare(1)}
{this.renderSquare(2)}
</div>
)
}
}
(三)方式二:函數式聲明,組件式調用
(1)在class外聲明 組件
const VoucherFrom = createForm((props) => {
// 函數式組件中接收參數和方法的方式如下:
const params = props.params;
props.propsFunction();
//函數式組件中寫函數的方式如下:
const changeValue = (e) => {
const value = {};
const values = '1';
// 調用傳遞過來的函數
props.changeValue(values, value)
}
return (
<div>
<span>{params}<span>
{/* 調用組件內自定義的方法如下 */}
<button οnclick={changeValue}></button>
</div>
)
})
(2)在class內調用
class ModalUse extends React.Component {
changeValue(values, value){}
render(){
const abc = 1;
return (
{/* 組件使用和參數方法傳遞 */}
<VoucherFrom params={abc} changeValue={::this.changeValue} />
)
}
}
// 以下部分和函數式組件沒有半毛錢關係,其只是一個注入。爲了完整性,我才寫出來的。
// 想了解,可以查看我的博客《React依賴注入說明(mapStateToProps/mapDispatchToProps)》
function mapStateToProps(state, ownProps) {
return {
}
}
function mapDispatchToProps(dispatch) {
return {
...bindActionCreators(action, dispatch),
}
}
export default connect(mapStateToProps, mapDispatchToProps)(ModalUse)
我在react看到了第一種方式的聲明,其實第二種也是ok的。就我個人而言,還是第二種方式的聲明比較容易。
不想用函數式組價,也可以正常定義組件(class–render()–return()).你懂就好了。