react点击按钮优雅的添加组件?

作者站长头像
站长
· 阅读数 9

我接到一个需求就是类似一个创建一个考试试卷,每次点击按钮,添加一个新的组件,这个组件可以是选择题,也可以是是非题,我现在想要实现这个按钮,因为这个生成试卷的功能比较复杂,所以我想要每一步代码都非常精简,优雅,目前看到以下代码可以实现功能,已经算是比较简练的了,但是还是发上来,看看大佬门有没有更好的实现思路,让代码更优雅。

import React from 'react';
import ReactDOM from 'react-dom';


class AppComponent extends React.Component {
  state = {
    numChildren: 0
  }
  
  render () {
    const children = [];
    
    for (var i = 0; i < this.state.numChildren; i += 1) {
      children.push(<ChildComponent key={i} number={i} />);
    };
    
    return (
      <ParentComponent addChild={this.onAddChild}>
        {children}
      </ParentComponent>
    );
  }
  
  onAddChild = () => {
    this.setState({
      numChildren: this.state.numChildren + 1
    });
  }
}

const ParentComponent = props => (
  <div className="card calculator">
    <p><a href="#" onClick={props.addChild}>Add Another Child Component</a></p>
    <div id="children-pane">
      {props.children}
    </div>
  </div>
);

const ChildComponent = props => <div>{"I am child " + props.number}</div>;


ReactDOM.render(<AppComponent/>, document.getElementById('root'));
回复
1个回答
avatar
test
2024-07-04

可以用map简化:

import React, { useState } from 'react';
import ReactDOM from 'react-dom';

const AppComponent = () => {
  const [components, setComponents] = useState([]);

  const onAddChild = (componentType) => {
    setComponents([...components, componentType]);
  };

  return (
    <div>
      <button onClick={() => onAddChild('Choice')}>Add Choice Question</button>
      <button onClick={() => onAddChild('TrueFalse')}>Add True/False Question</button>
      {components.map((componentType, index) => {
        switch (componentType) {
          case 'Choice':
            return <ChoiceQuestion key={index} />;
          case 'TrueFalse':
            return <TrueFalseQuestion key={index} />;
          default:
            return null;
        }
      })}
    </div>
  );
};

const ChoiceQuestion = () => {
  return <div>Choice Question</div>;
};

const TrueFalseQuestion = () => {
  return <div>True/False Question</div>;
};

ReactDOM.render(<AppComponent />, document.getElementById('root'));
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容