为了描述我的问题,我将首先显示 jsx 标记:
<Selector>
<ItemCategory title="A Special Category">
<Item title="PDF File" file="/file.pdf" />
</ItemCategory>
<Item title="PDF File 2" file="/file2.pdf" />
</Selector>
基本上我有一个要显示的 PDF 列表。项目可以属于某个类别,也可以不属于某个类别。在选择器组件中,我将当前选定的 PDF 作为状态。请参阅下面我当前的选择器组件。
export class Selector extends React.Component {
constructor(props) {
super(props);
this.state = {
currentSelection: null
};
}
render() {
var currentSelection = this.state.currentSelection || <NothingSelected />;
return (
<div className={"selector " + this.props.className}>
<div className="sidemenu">
<HeaderItem />
<div className="sidemenu-area">
{this.props.children}
</div>
</div>
<div className="selector-area">
{currentSelection}
</div>
</div>
);
}
}
现在我想如果您单击一个项目组件,则将当前选择更改为单击的项目。
知道如何添加 onClick 事件吗?
最佳答案
在此组件中,您需要一个 this.state.selectedFile 和 this.itemSelected。将 this.itemSelected 传递给 item 组件。将 this.state.selectedFile 传递给选定的组件。在 this.itemSelected 中传递来自项目组件 onClick 和 this.setState({selectedFile: passFile}) 的文件。
<Selector currentSelection={this.state.selectedFile}>
<ItemCategory title="A Special Category">
<Item title="PDF File" file="/file.pdf" onClick={this.itemSelected}/>
</ItemCategory>
<Item title="PDF File 2" file="/file2.pdf" onClick={this.itemSelected}/>
</Selector>
选择器组件。
export class Selector extends React.Component {
constructor(props) {
super(props);
}
render() {
var currentSelection = this.props.currentSelection || null;
return (
<div className={"selector " + this.props.className}>
<div className="sidemenu">
<HeaderItem />
<div className="sidemenu-area">
{this.props.children}
</div>
</div>
<div className="selector-area">
<Item title="PDF File 2" file={currentSelection} />
</div>
</div>
);
}
}
在item组件中;
render() {
if (this.props.file == null) return null;
return (
<div id='pdfDisplay' onClick={this.handleClick}></div>
)
}
_handleClick() {
if (this.props.onClick) this.props.onClick(this.props.file);
}
关于javascript - 在react中添加动态onClick事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32333835/