react 函数式组件
来源:互联网 发布:sql 给列添加默认值 编辑:程序博客网 时间:2024/05/23 17:38
函数式组件即是用函数的方式来声明组件,其特点在于组件可以直接写在页面内无需再起一个新的页面,同时只需要一个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()).你懂就好了。
阅读全文
1 0
- react 函数式组件
- React 当前组件与当前函数交互
- react-bits:无状态函数组件
- React组件中不要绑定匿名函数
- React 组件
- React组件
- react 组件
- React组件
- React 组件
- react 组件
- react组件
- react 组件
- React组件
- react---组件
- react 父子组件之间的通信和函数调用
- react 组件实例更新之函数调用顺序
- React 中被忽略的函数组件(Functional Components)
- react系列(6)组件生命周期钩子函数
- js encodeURI() 函数
- php 后期静态绑定的用法 static::
- PHP 发送邮件配置 转发自http://www.cnblogs.com/dee0912/p/5448350.html
- 自定义通知栏这样操作应该怎么搞?花式TextView操作在这里
- 关于halcon的多个二维码内容解析
- react 函数式组件
- HttpClient请求接口上传文件以及参数
- Leetcode Median of two sorted arrays解题
- Linux rsync服务配置及使用
- 日常笔记
- Android LayoutInflater.inflate()方法参数详解
- 8080端口被占用
- java 中 map 的用法总结
- tensorflow相关