gpt4 book ai didi

reactjs - 如何使这个 JSX 代码更加通用以避免 React 中的代码重用?

转载 作者:行者123 更新时间:2023-12-03 14:06:42 25 4
gpt4 key购买 nike

我对 react 还很陌生,我有一个问题。我有一些代码用一些信息填充一些选项卡,我需要一些帮助来创建一个可以多次重用的函数,而不是为每个选项卡重用相同的代码。

<div className="box box-default">
<div className="box-header with-border">
<h3 className="box-title">Strings Info</h3>
<div className="key-details">
<dl className="dl-horizontal">
<dt>Count</dt>
<dd>{count}</dd>
<dt>Average Length</dt>
<dd>{avg_length}</dd>
</dl>
</div>
</div>
<div className="box-header with-border">
<h3 className="box-title">Strings</h3>
<div>
<pre>
{this.props.raw_strings}
</pre>
</div>
</div>
</div>

我想我可以创建一个 populateTabs 函数,它可以将计数、平均长度和 props 中的原始字符串数据作为参数。每个选项卡的 count、avg_length 和 raw_strings 都不同,因为它们各自代表不同的字符串类型,因此我一直在为每个选项卡重复使用此 block ,尽管只更改了 3 个变量。在这种情况下减少代码重用的最佳方法是什么?谢谢!

最佳答案

代码可以提取到组件中。如果某些参数在某些情况下是通用的,则可以是接受通用参数的高阶组件:

const boxHOC = (count, avg_length) => props => (
<div className="box box-default">
<div className="box-header with-border">
<h3 className="box-title">Strings Info</h3>
<div className="key-details">
<dl className="dl-horizontal">
<dt>Count</dt>
<dd>{count}</dd>
<dt>Average Length</dt>
<dd>{avg_length}</dd>
</dl>
</div>
</div>
<div className="box-header with-border">
<h3 className="box-title">Strings</h3>
<div>
<pre>
{props.raw_strings}
</pre>
</div>
</div>
</div>
);

const OneTwoBox = boxHOC(1, 2);
const ThreeFourBox = boxHOC(3, 4);

关于reactjs - 如何使这个 JSX 代码更加通用以避免 React 中的代码重用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55034388/

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