函数式组件即是用函数的方式来声明组件,其特点在于组件可以直接写在页面内无需再起一个新的页面,同时只需要一个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 onclick={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()).你懂就好了。