ReactJS: 点击时动态添加组件

4

我有一个菜单按钮,当按下时必须添加一个新组件。它似乎有效(如果我手动调用函数来添加组件,则它们将被显示)。问题在于,如果我点击按钮,它们不会显示出来,我认为是因为我应该使用setState重新绘制它们。但是我不确定如何在另一个函数/组件中调用另一个组件的setState。

这是我的index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import Menu from './Menu';
import * as serviceWorker from './serviceWorker';
import Blocks from './Block.js';


ReactDOM.render(
    <div className="Main-container">
        <Menu />
        <Blocks />
    </div>
    , document.getElementById('root'));

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers:
serviceWorker.unregister();

然后我有Menu.js文件。

import React from 'react';
import './Menu.css';
import {blocksHandler} from './Block.js';

class Menu extends React.Component {

  constructor(props) {

    super(props);
    this.state = {value: ''};

    this.handleAdd = this.handleAdd.bind(this);

  }

  handleAdd(event) {
    blocksHandler.add('lol');
    console.log(blocksHandler.render());
  }

  render() {
    return (
      <div className="Menu">
        <header className="Menu-header">
          <button className="Menu-button" onClick={this.handleAdd}>Add block</button>
        </header>
      </div>
    );
  }
}

export default Menu;

最后是Block.js

import React from 'react';
import './Block.css';

// this function adds components to an array and returns them

let blocksHandler = (function() {
    let blocks = [];
    return {
        add: function(block) {
            blocks.push(block);
        },
        render: function() {
            return blocks;
        }
    }
})();

class Block extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            title: '',
            content: ''
        };

        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleChange(event) {
        this.setState({[event.target.name]: event.target.value});
    }

    handleSubmit(event) {
        alert('A name was submitted: ' + this.state.title);
        event.preventDefault();
    }

    render() {
      return (
        <div className="Block-container">
            <form onSubmit={this.handleSubmit}>
            <div className="Block-title">
                <label>
                    Block title:
                    <input type="text" name="title" value={this.state.value} onChange={this.handleChange} />
                </label>
            </div>
            <div className="Block-content">
                <label>
                    Block content:
                    <input type="text" name="content" value={this.state.value} onChange={this.handleChange} />
                </label>
            </div>
            <input type="submit" value="Save" />
            </form>
        </div>
      );
    }
}

class Blocks extends React.Component {

    render() {
        return (
            <div>
                {blocksHandler.render().map(i => (
                    <Block key={i} />
                ))}
            </div>
        )
    }
}


export default Blocks;
export {blocksHandler};

我是React的完全新手,所以我甚至不确定我的方法是否正确。感谢您能提供的任何帮助。


1
你可以使用props将父组件的状态传递给子组件。如果向子组件传递props包含许多子组件,则还可以使用上下文传递props。https://reactjs.org/docs/context.html 最好的解决方案是根本不使用React状态,而是使用更强大的状态管理系统,Redux非常适合此类问题。 - Keith
谢谢您的帖子。我正在尝试学习ReactJS,现在添加Redux可能会使事情变得太复杂了。我会查看您提供的链接。 - devamat
是的,如果你只是在学习的话,使用Redux可能会让事情变得更加混淆。我可以编写一个非常简单的代码片段,或许可以帮到你。 - Keith
2个回答

11

下面我搭建了一个非常简单的父/子组件结构...

父组件负责渲染按钮,这里我只使用了一个简单的数字数组。当你点击任何一个按钮时,它会调用父组件中的setState,并且这将导致父组件重新渲染其子组件。

注意:我还使用了React Hooks来完成这个过程,我觉得它们更自然、更容易使用。你也可以使用类,原理是相同的。

const {useState} = React;

function Child(props) {
  const {caption} = props;
  const {lines, setLines} = props.pstate;
  return <button onClick={() => {
    setLines([...lines, lines.length]);
  }}>
    {caption}
  </button>;
}

function Parent(props) {
  const [lines, setLines] = useState([0]);  
  return lines.map(m => <Child key={m} caption={`Click ${m}`} pstate={{lines, setLines}}/>);
}


ReactDOM.render(<React.Fragment>
  <Parent/>
</React.Fragment>, document.querySelector('#mount'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="mount"></div>


@devamat 没关系,如果上面的内容有任何不清楚的地方,请随时提问。如果您想在上面的片段中进行一些练习,请尝试更改它,以便每次仅启用最后一个按钮。 - Keith
对我有用。 关键是使用展开运算符并更新数组。 - pavan kumar v

0

不必将blocksHandlers作为单独的函数创建,您可以像下面这样将其放在Menu.js中

class Block extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            title: '',
            content: ''

        };
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }


    handleChange(event) {
        this.setState({[event.target.name]: event.target.value});
    }

    handleSubmit(event) {
        alert('A name was submitted: ' + this.state.title);

   event.preventDefault();
    }

    render() {
      return (
        <div className="Block-container">
            <form onSubmit={this.handleSubmit}>
            <div className="Block-title">
                <label>
                    Block title:
                    <input type="text" name="title" value={this.state.value} onChange={this.handleChange} />
                </label>
            </div>
            <div className="Block-content">
                <label>
                    Block content:
                    <input type="text" name="content" value={this.state.value} onChange={this.handleChange} />
                </label>
            </div>
            <input type="submit" value="Save" />
            </form>
        </div>
      );
    }
}

Menu.js

class Menu extends React.Component {

  constructor(props) {

    super(props);
    this.state = {value: '',blocksArray:[]};

    this.handleAdd = this.handleAdd.bind(this);

  }

  handleAdd() {
   this.setState({
        blocksArray:this.state.blocksArray.push(block)
     })

  }

renderBlocks = ()=>{
      this.state.blocksArray.map(block=> <Block/>)
 }
  render() {
    return (
      <div className="Menu">
        <header className="Menu-header">
          <button className="Menu-button" onClick={()=>this.handleAdd()}>Add block</button>
        </header>
    {this.renderBlocks()}

      </div>
    );
  }
}

export default Menu;


感谢您的帖子。我无法使这段代码工作。在blocksArray处出现错误:this.state.blocksArray.push(block),我将其更改为blocksArray:this.state.blocksArray.push('lol'),但没有成功,我仍然收到错误:TypeError:this.state.blocksArray.map不是一个函数。可能由于某种原因数组为空。 - devamat
实际上,在 handleAdd() 函数内,您需要为块提供配置,例如 this.state.blocksArray.push(/提供渲染 Block 组件所需的数据/)。 - Rajesh Kumaran

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接