使用 react json 的动态组件
Posted
技术标签:
【中文标题】使用 react json 的动态组件【英文标题】:Dynamic component using react json 【发布时间】:2021-12-26 01:02:58 【问题描述】:// JSON data is formed in this format.
chart:
functionalInfo: Array(5)
0: seedShapeDisplayText // one
materialsInfo: Array(1)
0:
igredientsInfo: Array(1)
0:
chartStatus: "minsu"
ingredientDisplayText:1
1: seedShapeDisplayText // two
materialsInfo: Array(1)
0:
igredientsInfo: Array(1)
1:
chartStatus: "Jeeny"
ingredientDisplayText:3
...
似乎很容易,但我不知道
Info.seedShapeDisplayText -> one two three four ..
one onClick <div> Hi Number Minsu, Bar : 1 </div>
two onClick <div> Hi Number Jenny, Bar : 3 </div>
综上所述,当点击'one li tag text'时,div会输出'one text'对应的'NumberStatus'值,functionInfolabels
对应的值。
点击第一个按钮我要打印第一个数组值Minsu和1。你想怎么写代码?
let functionInfolabels = ProductDetail && ProductDetail.chart?.functionalsInfo?.[0].materialsInfo?.[0].ingredientsInfo?.map(array => array.ingredientDisplayText);
console.log(functionInfolabels) // Array( 1,3,124 ..)
let NumberStatus = ProductDetail && ProductDetail.chart?.functionalsInfo?.[0].materialsInfo?.[0].ingredientsInfo?.map(array => array.chartStatus)
console.log(NumberStatus) // Array ( Minsu, Jenny, Youngmin, ...)
return (
ProductDetail && ProductDetail.chart?.functionalsInfo?.length ?
ProductDetail.chart?.functionalsInfo.map(Info => (
<li key=Info.id>Info.seedShapeDisplayText</li>
)) : <li>There is not</li>
// Info.seedShapeDisplayText -> one two three four ..
// one onClick <div> Hi Number Minsu, Bar : 1 </div>
// two onClick <div> Hi Number Jenny, Bar : 3 </div>
....
<div>
Hi Number NumberStatus // Minsu, Jenny, Youngmin, Jiho ...
<Bar
labels=functionInfolabels // 1, 3, 124 ....
/>
</div>
)
【问题讨论】:
【参考方案1】:维护selected
的状态变量,然后单击即可显示所需内容以供选择。
const Component = () =>
let functionInfolabels = [1, 3, 124];
let NumberStatus = ["Minsu", "Jenny", "Youngmin"];
const [selected, setSelected] = React.useState(-1);
return (
<div>
selected > -1 ? (
<div>`Hi Number $NumberStatus[selected], Bar : $functionInfolabels[selected]`</div>
) : (
<div>Not selected</div>
)
<div style= border: "1px solid lightgrey" ></div>
functionInfolabels.map((label, i) => (
<div key=label onClick=() => setSelected(i)>
label
</div>
))
</div>
);
;
ReactDOM.render(<Component />, document.getElementById("app"));
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<div id="app"></div>
【讨论】:
以上是关于使用 react json 的动态组件的主要内容,如果未能解决你的问题,请参考以下文章