如何在react . cloneelement中获得给定react组件的文本元素?



开发者给了我表格的标题:

const CustomersTable = () => {
var headers=<>
<th>Name</th>
<th>Age</th>
<th>Another text</th>
</>
return <Table
headers={headers}
/>
}

Table组件的代码:

const Table = ({headers}) => {
var clonedHeaders = React.Children
.toArray(headers.props.children)
.map(header => React.cloneElement(header, {
className: "text-gray-900 py-3 font-light text-xs"
}));
return <table>
<thead>
<tr>
{clonedHeaders}
</tr>
</thead>
</table>
}

我可以使用React.cloneElement添加属性到我收到的元素作为我的组件的道具。

但是,我希望能够更改这些接收到的元素的文本内容。

例如,我想调用我的语言环境转换函数对于表头元素,自动。现在,如果开发人员想让他们的表多语言化,他们应该这样写:
var headers = <>
<th>{t('Name')}</th>
<th>{t('Age')}</th>
<th>{t('Other text')}</th>
</>

我想把t(text)函数集中到所有headersprop上。我可以这么做吗?

您可以对header的子元素使用与对header本身相同的技术:

const clonedHeaders = React.Children
.toArray(headers.props.children)
.map(header => React.cloneElement(header, {
className: "text-gray-900 py-3 font-light text-xs",
children: React.Children.toArray(header.props.children).map(child => {
return typeof child === "string" ? t(child) : child;
})
}));

生活的例子:

const {useState} = React;
function t(english) {
// Just so we can see that it happens
return english.toLocaleUpperCase();
}
const CustomersTable = () => {
var headers=<React.Fragment>
<th>Name</th>
<th>Age</th>
<th>Another text</th>
</React.Fragment>;
return <Table
headers={headers}
/>;
};
const Table = ({headers}) => {
const clonedHeaders = React.Children
.toArray(headers.props.children)
.map(header => React.cloneElement(header, {
className: "text-gray-900 py-3 font-light text-xs",
children: React.Children.toArray(header.props.children).map(child => {
return typeof child === "string" ? t(child) : child;
})
}));
return <table>
<thead>
<tr>
{clonedHeaders}
</tr>
</thead>
</table>;
};
ReactDOM.render(<CustomersTable />, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>

这个例子没有做任何递归,所以它不会处理<th><span className="something">Name</span></th>。如果你想处理它,你必须写一个递归函数来处理它,但它将沿着相同的行。

最新更新