解锁 React 组件化新姿势 - react-call-return
最早的时候,antd 的 const columns = [ { dataIndex: 'name',title: 'Name' },{ dataIndex: 'age',title: 'Age' },{ dataIndex: 'address',title: 'Address' } ] <Table columns={columns} data={data} /> 只要把列定义和数据传给 class Table extends React.Component { render() { const { columns,data } = this.props; return ( <table> <thead> <tr> {columns.map(col => <th key={col.dataIndex}>{col.title}</th> )} </tr> </thead> <tbody> {data.map(item => ( <tr key={item.id}> {columns.map(col => <td key={col.dataIndex}>{item[col.dataIndex]}</td> )} </tr> ))} </tbody> </table> ); } } 后来,有人就觉得这样写不够 React 啊,我想要用 JSX 来定义列啊。
好吧,那我们把上面的 const Column = () => {}; class Table extends React.Component { static Column = Column; render() { const { children,columns,data } = this.props; this.columns = columns || React.Children.map(children,(child) => ({ dataIndex: child.props.dataIndex,title: child.props.title,})) return ( <table> <thead> <tr> {this.columns.map(col => <th key={col.dataIndex}>{col.title}</th> )} </tr> </thead> <tbody> {data.map(item => ( <tr key={item.id}> {this.columns.map(col => <td key={col.dataIndex}>{item[col.dataIndex]}</td> )} </tr> ))} </tbody> </table> ); } } 这里我们定义了一个什么都不干的 可是,过了段时间,又有人不满意了。
既然现在支持 JSX 的方式定义列了,那我就想封装自己的 这个问题,一直没有很好的解法。但是,就在昨天,随着 React 16.1 的发布,React Team 还发布了两个实验性的包
我们先来用这两个方法重新实现一下上面的 const Column = (props) => unstable_createReturn(props); class Table extends React.Component { static Column = Column; render() { const { children,data } = this.props; return ( <table> <thead> <tr> {unstable_createCall(children,(props,columns) => ( columns.map(col => ( <th key={col.dataIndex}>{col.title}</th> )) ),this.props)} </tr> </thead> <tbody> {data.map(item => ( <tr key={item.id}> {unstable_createCall(children,columns) => ( columns.map(col => ( <td key={col.dataIndex}>{item[col.dataIndex]}</td> )) ),this.props)} </tr> ))} </tbody> </table> ); } } 可以看到, react-call-return 的出现,让我们在组件设计上有了更多的可能性,JSX 不再需要映射 DOM,而是可以直接来表达数据。 以上所有演示代码,可以在这里找到 https://github.com/yesmeck/neotable (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- ReactNative学习笔记(二)Flex布局
- 使用Ajax方法实现Form表单的提交及注意事项
- Flash2D游戏Blitting技术学习笔记
- ruby-on-rails – 将capybara从1.0.1升级到1.1.4会使databa
- 使用boost :: python从C创建python collections.namedtuple
- ruby – hitimes在Windows 8.1上运行jekyll服务时需要输入错
- clojure实例?单一论证
- c# – 为什么Enum.ToString()没有返回正确的枚举名称?
- flex iframe 嵌套HTML,as和js间的交互
- 用于获取存储在单个表中的n级父子关系的Postgresql查询