无法想出创建以下函数的方法。我目前将数据(本地 json)加载到 li
中。单击后,我想向单击的带有数据的 li
元素添加一个新组件。
例子:
<ul>
<li> 1 </li>
<li> 2 </li>
<li>
3
<div id="data">
<!-- appended data -->
</div>
</li>
</ul>
单击另一个 li
后,应删除先前附加的元素并添加到新单击的 li
中。 (行切换)
如果有人能在正确的 React 方向上踢我。
import React, { Component } from 'react';
import Flowers from 'flowers.json';
class Flowers extends React.Component {
constructor(props) {
super(props);
this.state = {
isToggleOn: true
};
this.onClick = this.handleClick.bind(this);
}
handleClick = (e) => {
console.log(this);
console.log(e);
console.log('li item clicked! ' + e.currentTarget);
// appends to clicked div
e.currentTarget.style.backgroundColor = '#ccc';
}
render() {
const List = Flowers.map((flower) =>
<li onClick={this.handleClick.bind(this)} key={flower.id} id={flower.id}>
{flower.name}
</li>
);
return(
<ul>{List}</ul>
);
}
}
class App extends Component {
render() {
return (
<Flowers />
);
}
}
export default App;
最佳答案
您可以将活跃的花的 ID 添加到您的状态。 例如。
this.state = { ActiveFlowerID: null }
所以当没有 ActiveFlower 时 none 是打开的。 在 handle click 方法上对状态进行更改,并使用与花 ID 和状态匹配的 if 来呈现您的花的附加数据。
希望这对您有所帮助。
关于javascript - React JS 将组件添加到特定的点击行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42650884/