gpt4 book ai didi

javascript - React - 在组件内动态创建列表项

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

有没有办法将动态 li 元素添加到我的 ul 列表中?我想通过单击按钮添加我的 li。这是示例代码

class Component1 extends React.Component {

constructor() {
super();
}

add() {
let ul = document.getElementById('mylist');
let li = document.createElement('li');
li.appendChild(document.createTextNode({some_variables});
ul.appendChild(li);
}
render() {
return (
<a href="#" onClick={() => this.add()}>Add</a>
<ul id="mylist">
/* dynamic list ITEM */

</ul>
);
}
}

ReactDOM.render(<Component1 />, document.getElementById('root'));

当然,当前函数 add() 不适用于 React

最佳答案

在使用 React 时,我们不会像通常使用其他库(如 jQuery)那样“接触”DOM。
React 最好的核心功能之一是虚拟 DOM,Reconciliation & diffing algorithm

React builds and maintains an internal representation of the rendered UI. It includes the React elements you return from your components. This representation lets React avoid creating DOM nodes and accessing existing ones beyond necessity, as that can be slower than operations on JavaScript objects. Sometimes it is referred to as a “virtual DOM”

在 React 中,您创建组件(函数)来呈现/返回 jsx(标记)。
您的场景的一个简单示例可能是:

const ListItem = ({ value, onClick }) => (
<li onClick={onClick}>{value}</li>
);

const List = ({ items, onItemClick }) => (
<ul>
{
items.map((item, i) => <ListItem key={i} value={item} onClick={onItemClick} />)
}
</ul>
);

class App extends React.Component {
constructor(props) {
super(props);
this.state = {
inputValue: '',
fruites: ['Apple', 'Banana', 'Orange']
};
}

onClick = () => {
const { inputValue, fruites } = this.state;
if (inputValue) {
const nextState = [...fruites, inputValue];
this.setState({ fruites: nextState, inputValue: '' });
}
}

onChange = (e) => this.setState({ inputValue: e.target.value });

handleItemClick = (e) => {console.log(e.target.innerHTML)}

render() {
const { fruites, inputValue } = this.state;
return (
<div>
<input type="text" value={inputValue} onChange={this.onChange} />
<button onClick={this.onClick}>Add</button>
<List items={fruites} onItemClick={this.handleItemClick} />
</div>
);
}
}


ReactDOM.render(<App />, document.getElementById("root"));
<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="root"></div>

关于javascript - React - 在组件内动态创建列表项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46514351/

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