简体   繁体   English

在 React 中单击按钮添加和删除 HTML 元素

[英]Add and Remove HTML Elements on Button Click in React

What's the best uncomplicated way to achieve this jQuery fiddle using just React without using jQuery or any other libraries?仅使用 React 而不使用 jQuery 或任何其他库来实现此 jQuery小提琴的最佳简单方法是什么? I don't quite have the ReactJS skills yet, and was wondering if there was a way to create and delete elements dynamically.我还不太具备 ReactJS 技能,想知道是否有一种方法可以动态创建和删除元素。

I was thinking of creating a我正在考虑创建一个

this.state = { "inputs": ["<input type="text" /><input type="checkbox" />"] }

state variable array that holds the HTML when added, giving each one a unique key based on the index and then .map() it, but am unsure whether there's an easier way to achieve this and am unsure on how to delete each element as such.添加时保存 HTML 的状态变量数组,根据索引为每个人提供一个唯一的键,然后 .map() 它,但我不确定是否有更简单的方法来实现这一点,也不确定如何删除每个元素.

Would love any help or feedback, thanks!希望得到任何帮助或反馈,谢谢!

Here is a "React" way to do this, I'm not a React expert, so the code could be better, would accept corrections.这是一种“反应”方式来做到这一点,我不是反应专家,所以代码可以更好,会接受更正。

  • Yes, react has more boilerplate codes, because you don't handle DOM directly and there is less "magic" which means you have more control overall.是的,react 有更多样板代码,因为你不直接处理 DOM,而且“魔法”更少,这意味着你有更多的控制权。 (specially as a controlled component) (特别是作为受控组件)
  • States should be as minimum as possible, you just have to hold the pure data, other decorative stuff let components to handle them.状态应该尽可能少,你只需要保存纯数据,其他装饰性的东西让组件来处理它们。
  • depends on the situation, you may want to separate the Row component into 2 separate components with more props.视情况而定,您可能希望将Row组件分成 2 个具有更多道具的独立组件。
  • ??? ??? more suggestions?更多建议?

UPDATE: after workin with React everyday for the last past 3 years, I found there are some bad practices on the previous code, I have update the code to be cleaner hopefully it helps you.更新:在过去的 3 年里每天都在使用 React 之后,我发现以前的代码有一些不好的做法,我已经更新了代码,希望它可以帮助你。

 const Row = function(props){ const {checked, value, onChange, onChecked} = props; return ( <div> <input type="checkbox" checked={checked} onChange={onChecked} /> <input type ="text" value={value} onChange={onChange}/> </div> ); } class App extends React.Component { constructor(props){ super(props); this.state = { rows: [ {value: 'row1', checked: false}, {value: 'row2', checked: true}, {value: 'row3', checked: false}, ] }; } updateValue = (e, idx) => { const rows = [...this.state.rows]; // copy array because we don't want to mutate the previous one rows[idx].value = e.target.value; this.setState({ rows, }); } onChecked = (idx) => { const rows = [...this.state.rows]; // copy array because we don't want to mutate the previous one rows[idx].checked = !rows[idx].checked; this.setState({ rows, }); } addRow = () => { const rows = [...this.state.rows, {value:'', checked: false} ]; this.setState({ rows, }); } deleteRows = () => { this.setState({ rows: this.state.rows.filter(e => !e.checked) }); } render(){ return( <div> {this.state.rows.map((row, idx) => { return( <Row key={idx} value={row.value} checked={row.checked} onChange={(e) => this.updateValue(e, idx)} onChecked={() => this.onChecked(idx)} /> ) }) } <button onClick={this.addRow}> add </button> <button onClick={this.deleteRows}> delete </button> </div> ); } } ReactDOM.render( <App />, document.getElementById('app') );
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.6/umd/react.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.development.js"></script> <div id="app"> </div>

Just use the old plain JS way只需使用旧的纯 JS 方式

 var elem = document.getElementById("button_" + id);
 elem.parentNode.removeChild(elem);

In my opinion, keep the element you want to create in a variable .在我看来,将要创建的元素保留在变量中。 every time you want to create a element push() it into a array and then map it through the array to render it, if you want to remove you can use pop() to remove the last item in the array.每次你想创建一个元素 push() 到一个数组中,然后通过数组映射它来渲染它,如果你想删除你可以使用 pop() 删除数组中的最后一项。

Note: you have to use dangerouslySetInnerHTML to render the element when it is a string.注意:当元素是字符串时,您必须使用危险的SetInnerHTML 来呈现元素。

Happy Coding !快乐编码!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM