2017-08-24 191 views
1

我可以在reactjsonClick -event上创建新组件。 我已经试过这样:React - 返回组件onClick事件

我的部件,其中该点击事件发生:

... 
<li onClick={this.edit.bind(this)}><span className="glyphicon glyphicon-pencil"></span> Edit entry</li> 
... 

这是edit方法:

edit(event) { 
     return <CreateFreightEntryModal key={"freightEditModal" + this.state.freight.ID} openOnStartup="true" modalId={"freightEditModal" + this.state.freight.ID} /> 
    } 

不引发错误,但该组件没有被创建。我做错了什么,或者这不是真的推荐?

+0

onlick函数根本不编辑状态,你只是返回一个组件。你应该让edit函数切换一个'edit'状态,使'CreateFreightEntryModal'组件被渲染,而不是通常在那里。 – Joe

+1

你在哪里期待返回的元素会被渲染?使用状态布尔和onclick编辑按钮使用'setState'并用true更新,使用该变量渲染组件,检查[文档的有条件渲染部分](https://facebook.github.io/react/docs /conditional-rendering.html) –

+0

如果这只是一个元素,请将标志保持在状态并使用'{flag? component:null}'in render – Rajesh

回答

3

在反应中,显示模式有点棘手,因为它的本质。

edit() { 
    this.setState({ showModal: true }) 
} 

render() { 

    return (
     <div> 
      { this.state.showModal && <CreateFreightEntryModal props/> } 
     </div> 
    ) 

} 
+0

是的,我已经知道这个解决方案,但是我有一个超过600个条目的列表。我不想为此列表的每个条目创建一个自己的组件。我的想法是创建一个组件,当一个条目被点击。它节省了很多加载时间,而不是创建一个自己的组件的foreach入口。这可能吗? –

+0

好的。现在我明白你的方式了。谢谢你的帮助。 –

1

你最好渲染状态组件作为@Ozgur GUL在 回答说。

但是,如果您必须动态呈现某些内容,则可以这样做。

import ReactDOM from 'react-dom'; 

... 
edit() { 
    ReactDOM.render(<CreateFreightEntryModal key={"freightEditModal" + this.state.freight.ID} openOnStartup="true" modalId={"freightEditModal" + this.state.freight.ID} />); 
}