React渲染一个组件,然后单击另一个React组件

React render a component on click after another react component

本文关键字:组件 React 然后 另一个 单击 一个      更新时间:2023-09-26

非常新的反应。我正在创建一个带有一系列下拉列表的页面,其想法是当你在一个下拉列表上选择一个选项时,在它的正下方会附加一个相同的下拉列表

所有的div和select/options都是React组件,我试图给其中一个提供初始状态"firstTime==true",然后当你点击一个选项时(如果是true),它会在event.target.parentElement下面呈现另一个<Dropdown />元素。

var Dropdown = React.createClass({
  getInitialState: function () {
    return{firstTime: true};
  },
  change: function(event){
    var x = event.target;
    this.state.firstTime==true ? ReactDOM.render(<Dropdown options={OptionChoices} dropdownClass="Poop" />, wrapper) : console.log("oh well");
    this.setState({firstTime: false});
  },
  render: function() {
    return (
      <select onChange={this.change} className={this.props.dropdownClass}>
        {this.props.options.map(function(option){
          return (
              <Option value={option.value} key={option.value}>{option.label}</Option>
            );
        })}
    </select>
    );
  }
});

不幸的是,它不断提出"目标容器不是DOM元素"。这是有道理的,因为我试图将它放在react生成的元素中,但对我尝试做的事情没有太大帮助。

感谢您的任何帮助,如果这是一个非常基本的问题,我们深表歉意。

Fiddle:https://jsfiddle.net/y4wfLy1z/

我建议在第一次调用时始终同时渲染select选项(第一个和渲染中的那个)和隐藏第二个选项。

因此,在第一次调用的更改事件中,您可以更改隐藏第二个元素的可见性的状态变量(this.state.dropdownClass)。更改时,您将className设置为所需的类属性(this.props.dropdownClass)

在ES6中,这看起来如下:

export default class Dropdown extends React.Component {
    constructor() {
        super();
        this.firstTime = true;
        this.first_options = [{value: 'first1', label: 'First Option 1'}, {value: 'first2', label: 'First Option 2'}];
        this.state = {dropdownClass: 'hide'};
    }
    change(event) {
        console.log('change');
        this.setState({dorpdownClass: this.props.dropdownClass});
    }
    render() {
        return (
           <div>
               <select onChange={this.change.bind(this)} className='Poop'>
                    {this.first_options.map(function (option) {
                        return (
                            <option value={option.value} key={option.value}>{option.label}</option>
                        );
                    })}
                </select>
                <select onChange={this.change.bind(this)} className={this.props.dropdownClass}>
                    {this.props.options.map(function (option) {
                        return (
                            <option value={option.value} key={option.value}>{option.label}</option>
                        );
                    })}
                 </select>
           </div>
       );
    }
}