gpt4 book ai didi

javascript - 每个 react 组件都应该在一个单独的文件中吗?

转载 作者:搜寻专家 更新时间:2023-11-01 04:22:38 25 4
gpt4 key购买 nike

它们似乎在文档示例中的同一个文件中:https://facebook.github.io/react/docs/thinking-in-react.html .

在这样的情况下,您的某些组件非常小,您如何将组件分解成页面?

class ProductCategoryRow extends React.Component {
render() {
return (<tr><th colSpan="2">{this.props.category}</th></tr>);
}
}

class ProductRow extends React.Component {
render() {
var name = this.props.product.stocked ?
this.props.product.name :
<span style={{color: 'red'}}>
{this.props.product.name}
</span>;
return (
<tr>
<td>{name}</td>
<td>{this.props.product.price}</td>
</tr>
);
}
}

class ProductTable extends React.Component {
render() {
var rows = [];
var lastCategory = null;
this.props.products.forEach((product) => {
if (product.name.indexOf(this.props.filterText) === -1 || (!product.stocked && this.props.inStockOnly)) {
return;
}
if (product.category !== lastCategory) {
rows.push(<ProductCategoryRow category={product.category} key={product.category} />);
}
rows.push(<ProductRow product={product} key={product.name} />);
lastCategory = product.category;
});
return (
<table>
<thead>
<tr>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>{rows}</tbody>
</table>
);
}
}

最佳答案

您可能不必将每个组件都放在自己的文件中 - 例如,您可以使用无状态功能组件进一步拆分 ProductRow 组件:

const ProductName = (product) => 
<span style={{color: product.stocked ? 'black' : 'red'}}>
{ product.name }
</span>

const ProductRow = (product) =>
<tr>
<td>{ ProductName(product) }</td>
<td>{ product.price }</td>
</tr>

关于javascript - 每个 react 组件都应该在一个单独的文件中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42988768/

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