gpt4 book ai didi

javascript - 如何安排 React 子组件的顺序?

转载 作者:行者123 更新时间:2023-11-30 14:19:19 25 4
gpt4 key购买 nike

react-semantic-ui , 我制作了一个可搜索、可分页的 Table React 组件

工作示例:https://codesandbox.io/s/23q6vlywy

用法

<PaginationTable
items={[
{
id: 1,
name: "test-item-1 ???"
},
{
id: 2,
name: "test-item-2"
},
{
id: 3,
name: "test-item-3"
}
]}
columnOption={[
{
header: "idHeader",
cellValue: "id",
onItemClick: item => {
alert(item.id);
},
sortingField: "id"
},
{
header: "Name~",
cellValue: item =>
`*custom text cannot be searched* property can item.name => ${
item.name
} `,
onItemClick: item => {
alert(item.name);
},
sortingField: "name"
}
]}
initSortingField={"id"}
initSortingOrderAsc={false}
pagination
itemsPerPage={2}
searchKeyProperties={["id", "name"]}
/>

但是这个组件目前只能有一定的顺序

 1.SearchBar on top
2.Table on middle
3.PaginationBar on bottom

而且实际上,我并没有在Component中写3个子组件,SearchBar , Table , PaginationBar

所以我很难重写它来渲染 Prop 的方式来改变顺序,如下所示

<PaginationTable {...props}>
{({ SearchBar, Table, PaginationBar })=>
<div>
<SearchBar />
<Table />
<SearchBar />
</PaginationTable>
</div>
</PaginationTable>

因为当我尝试更改渲染 Prop 时,我首先必须独立编写 3 个组件,这意味着我必须更改 this 下的所有变量。 ( this.state, this.props, this.xxxFunction ) 到其他东西。

例如:

在 , 我可以使用

 <Input onChange={()=>{
this.setState({ searchBarText: e.target.value });
}}/>

但是如果我将它改为 3 个组件,我必须将它重写为类似的东西

const SearchBar = ({onTextChange}) => <Input onChange= 
{onTextChange}/>

<SearchBar onTextChange={()=>{
this.setState({
searchBarText: e.target.value
});
}} />

有什么方法可以优雅地调整子组件的顺序,或者有什么方法可以更轻松地编写渲染 Prop ?

更新于 2018.10.27 17:36 +08:00

我修改了<PaginationTable>的渲染功能如下,但在 <SearchInput> 上输入时鼠标光标将失去焦点

render(){
const SearchBar = ()= (<Input onChange={()=>{...} />);
const TableElement = ()=>(<Table {...} > ... </Table>);
const PaginationBar = ()=>(<Menu {...} > ... </Menu>);
enter code here
return(
<React.Fragment>
{this.props.children({ SearchBar,TableElement, PaginationBar })}
</React.Fragment>)};

然后我发现,通过这种方式,每次我的状态更新时 DOM 都会更新,因为每次渲染都会通过 const SearchBar = ()=>(...) 创建一个新的组件引用。 .

感谢@Ralph Najm

如果我如下声明子组件,DOM 不会每次都更新。

render(){
const SearchBar = (<input onChange={...} />);
const TableElement = (<Table .../>);
const PaginationBar = (<Menu .../>);
//... same as above
}

通过这种方式,我可以更改我的组件来渲染 Prop ,以便非常容易地安排顺序。

提前致谢。

最佳答案

在 PaginationTable 组件中更改您的 render 函数并在 return 语句之前,将元素分配给变量(SearchBar、Table、PaginationBar 等...),然后在 render 函数中引用这些变量.

我在这里修改了你的例子https://codesandbox.io/s/vy4799zp45

关于javascript - 如何安排 React 子组件的顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53019991/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com