单击按钮将组件添加到另一个组件 [英] Add a component to another component on button click

查看:107
本文介绍了单击按钮将组件添加到另一个组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个页面,如果用户单击add more按钮,则应添加一个与用户单击次数相同的文本框

I'm creating a page that if user clicks add more button a text box should be added as many time the user clicks

我在创建texbox的位置创建了一个组件.我尝试在单击按钮时将此组件呈现为另一个组件,但是它不起作用.为什么?

I have created a component where I've created texbox. I've tried to render this component into another component on button click but it is not working. why?

class Addmore extends React.Component {
  render() {
    return (
      <div>
        <label className="float-left"> CC</label>
        <input type="text" class="form-control" />
      </div>
    );
  }
}

class abc extends React.Component {
    constructor(props)
    {
        super(props);
    }
  state = {
    addcomp: false
  };

  click() {
    this.setState({
        addcomp: true,
      });
     var x= document.getElementById("more");
     x.parentNode.appendChild(<Add/>);
  }
  render() {
    return (
            <div class="row">
            <div class="col-3">
            <label className="float-left"> BU</label>
             <input type="text" class="form-control" />


             <div id="more">

              //HERE I HAVE TO RENDER ADDMORE
                         COMPONENT

             </div>

             <div class="col-3">
                  <button type="button" onClick={this.click.bind()}>
                                Add more
                  </button>
             </div>
    );
  }
}
export default abc;

推荐答案

您应该让React渲染所有内容,而您的工作只是告诉React要渲染什么,以及多少次.为此,可以使用counter跟踪应该在<Example>组件内部注入"多少动态添加的内容.

You should let React render everything, and your job is only to tell React what to render and, in your case, how many times. For that, a counter can be used to track how many dynamically-added should be "injected" inside the <Example> component.

这里需要思想转变,因为在您的示例中,您来自一个认为单击处理程序本身应该修改DOM的地方,而在React中这是一个反模式.

A mindshift is needed here, since in your example you are coming from a place where you think that the click handler itself should modify the DOM, and in React that is an antipattern.

相反,您应该使用 state ,这意味着点击处理程序应更新主机组件的状态,这将触发重新渲染(这是React的工作方式),并且在在下一个渲染周期,您添加的组件将被渲染与计数器值一样多的次数,因为该计数器更改是触发重新渲染的原因.

Instead, you should work with state, and that means the click handler should update the state of the host component and that will trigger a re-render (this is how React works) and in the next render cycle, your added component will be rendered as many times as the counter value, because that counter change is what triggered the re-rendering.

在React中,道具&状态是触发重新渲染的方式,任何DOM修改都应通过更改内部组件的状态或通过从父组件发送不同的道具来进行.

In React, the props & state are the way to trigger re-render and any DOM modification should be done by changing the internal component's state, or by sending different props, from the parent component.

在下面的示例中,我使用,但是使用

In the below example I do not use Classes, but use Hooks instead, because I've stopped using class altogether once hooks were released, because I think it's cleaner:

// Get a hook function
const {useState, useCallback} = React;

// The added element component
const AddedElement = () => <div><input placeholder='text box' /></div>

// The "app" component
const Example = () => {
  const [count, setCount] = useState(0);

  return <div>
    <button onClick={() => setCount(count + 1)}>
      Click me
    </button>
    { Array(count).fill(<AddedElement />) }
  </div>
};

// Render 
ReactDOM.render(
  <Example />,
  document.getElementById("react")
);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>

如果您对如何重复渲染感兴趣,请在以下问题中针对此问题写一个答案:

If you are interested in how to repeatedly render the same component, I've written an answer about this in this question: How can I render repeating React elements?

这篇关于单击按钮将组件添加到另一个组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆