简体   繁体   English

React.js将组件插入子级

[英]React.js Inserting Component Into Child

<div>
   <p>Test</p>
</div>

<button onClick={AddPara()}> Add New Paragraph </button>

function AddPara (){
   return(
      <div>
         <p> New Para </p>
      </div>
   )
}

I am trying to get the new paragraph under the main Div that includes original paragraph ( <p>test</p> ), every time the button is clicked. 我试图每次单击按钮时在包含原始段落( <p>test</p> )的主Div下获得新段落。 I tried using ReactDOM.render however it throws me an error telling me to change the state rather using the DOM. 我尝试使用ReactDOM.render,但是它引发了一个错误,告诉我更改状态而不是使用DOM。

How would I do this? 我该怎么做?

I am trying to get the component dynamically rather than setting a specific limit of <p> . 我试图动态获取组件,而不是设置<p>的特定限制。 Instead of just having an extra <p> I am trying to insert <p> every time the button is click dynamically 我试图每次动态单击按钮时都插入<p>而不仅仅是增加一个<p>

end result I am trying to get: 最终结果,我试图得到:

<div> 
   <p> Test </p>
   <p> New Para </p>
   <p> New Para </p>
    ... keep adding <p>New Para</p> on button click
</div>

Is this demo what you want? 这个演示是您想要的吗? If yes, please check this answer as accepted :) 如果是,请检查此答案是否被接受:)

Hope this helps, Have a nice day! 希望对您有帮助,祝您有美好的一天!

 class App extends React.Component { constructor (props) { super(props); this.state = { items: [] }; this.addParagraph = this.addParagraph.bind(this); } addParagraph() { this.setState({ items: [...this.state.items, 'New Para'] }); } render() { return <div> <p>Test</p> {this.state.items.map((item, index) => <p key={'child_' + index}>{item}</p> )} <button onClick={this.addParagraph}>Add paragraph</button> </div> } } ReactDOM.render(<App />, document.getElementById('app')); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="app"></div> 

If I understand correctly, you want to do something like this - 如果我理解正确,您想做这样的事情-

class AddPara extends React.Component {
   state = {
     paragraphText: "New Para"
   };

   addParagraph = () => {
      this.setState({ paragraphText: "Test" });
   }

   return(
      <div>
         <p>{this.state.paragraphText}</p>
         <button onClick={this.addParagraph}>Add New Paragraph</button>
      </div>
   )
}

When you click the button, it will now replace the content inside the paragraph with Test :) 当您单击按钮时,它将立即用Test :)替换段落中的内容。

I am guessing you are pretty new to react. 我猜你是个新手。 That's the case, I would highly encourage you to read the documentation a bit. 就是这种情况,我强烈建议您稍微阅读一下文档。 Now about your issue, You just add a setState in the button click function, and show the new para based on the value change. 现在,关于您的问题,您只需在按钮单击功能中添加setState,然后根据值更改显示新的参数。

state = {
 showTime: 0
}
render () {
// Other code
<div>
   <p> Test </p>
{new Array(this.state.showTime).map(() => <p> New Para </p>)}
</div>

<button onClick={AddPara()}> Add New Paragraph </button>
}

function AddPara (){
   this.setState({showTime: this.state.showTime + 1});
}

From your question, you want to add a new paragraph on button click. 根据您的问题,您想在按钮单击时添加一个新段落。

To do this you need to map over an array in your state to render each item in the array. 为此,您需要在状态下map一个数组以呈现数组中的每个项目。

When you want to add a new paragraph, simply, add the new paragraph to the current state. 要添加新段落时,只需将新段落添加到当前状态即可。

class App extends Component {
  state = {
    paragraphs: ["hello world"]
  };

  addParagraph = () => {
    this.setState({
      paragraphs: [...this.state.paragraphs, "new paragraph"]
    });
  };

  render() {
    return (
      <div className="App">
        <h1>Hello CodeSandbox</h1>
        <h2>Start editing to see some magic happen!</h2>
        {this.state.paragraphs.map(paragraph => (
          <p>{paragraph}</p>
        ))}
        <button onClick={this.addParagraph}>Add Paragraph</button>
      </div>
    );
  }
}

Here is a Codesandbox Example 这是一个Codesandbox示例

It should be noted though, that you can use the updater function within setState to ensure you do not do multiple calls during the same cycle. 但应注意,可以在setState中使用updater函数,以确保您在同一周期内不进行多次调用。

addParagraph = () => {
    this.setState(prevState => ({
      paragraphs: [...prevState.paragraphs, "new paragraph"]
    }));
  };

See setState Api docs for more info. 有关更多信息,请参见setState Api文档

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

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