【问题标题】:is there a way to append a component using react?有没有办法使用反应附加组件?
【发布时间】:2020-05-09 21:15:29
【问题描述】:

基本上,我希望用户单击一个按钮,该按钮将向页面添加一个<Message /> 组件。他们可以继续点击按钮,更多的<Message />组件将被创建。

伪代码

render() {
    return (
        <button onClick={this.addMessage}></button>
        <Message />
        //basically a new message component would spawn here so it would look like this if the person clicked the button 3 times

        <Message /> 
        <Message /> 
        <Message /> 

    );

}

addMessage = () => {
   create new Message component
}

【问题讨论】:

  • 提示...每次点击都会添加到一个状态数组,然后你在 render() 中映射该数组,每次迭代都会创建一个新的&lt;Message/&gt;
  • 正如@charlietfl 所说,用户的每个操作都会设置一个新数组,其中包含一个额外的项目:)
  • 这能回答你的问题吗? React.js: How to append a component on click?

标签: javascript reactjs react-component


【解决方案1】:

使用状态对象来做你想做的事。例如,

const [messages, setMessages] = useState([]);
const wasClick = (data) => {
    setMessages([...messages, data]);
}

然后在渲染函数中

messages.map(message=><Message message={message}/>)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-20
    • 2017-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多