[英]How to transfer a state array to props
所以我有2個React文件,一個App.js和一個category.js。 當我將數組傳輸到category.js時,它顯示了大量文本,而不是將其拆分為不同的數組按鈕。 我嘗試搜索,但不知道該怎么做。 有人可以解釋嗎?
這是班級的應用程序
class App extends React.Component {
Object.keys(data.categories).forEach((category,index) => {
arr.push(data.categories[index].name);
})
render() {
return (
<div>
<Categories
categoryName = { this.state.categoryName }
/>
</div>
這是使用道具的類別
const Categories = props => (
<div>
<br />
{ props.categoryName && <button> { props.categoryName } </button>}
</div>
);
您需要映射您的categoryName
數組
const Categories = props => (
<div>
<br />
{ props.categoryName &&
props.categoryName.map(name => <button>{name}</button>)}
</div>
);
假設類別是組件狀態中的對象數組,請map
狀態類別,並在數組的每次迭代中返回Category
組件。
function Category({ categoryName }) { return (<button>{categoryName}</button>); } class App extends React.Component { constructor(props) { super(props); this.state = { categories: [ { categoryName: 'Bob', type: 'string' }, { categoryName: 'Trevor', type: 'number' }] }; } render() { return ( <div> {this.state.categories.map(category => { return <Category categoryName={category.categoryName} /> })} </div> ) } } ReactDOM.render( <App />, document.getElementById('container') );
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="container"></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.