在react中添加动态onClick事件



为了描述我的问题,我将首先展示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>
    );
  }
}

现在我想如果你点击一个Item- component来改变当前选择到被点击的Item。

知道如何添加onClick事件吗?

在这个组件中你想要一个this.state. selectedfile和this. itemselected。通过这个。itemSelected到项目组件。将this.state.selectedFile传递给被选择的组件。在这。itemSelected从项目组件onClick和this传递文件。设置状态({selectedFile: passedFile}) .

<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);
    }

你可以给父元素添加一个click处理程序,然后在click处理程序中进行过滤:

...
<div className="sidemenu-area" oncClick={this.selectItem}>
...

selectItem应该看起来像:

selectItem (e) {
  this.setState({
    currentSelection: e.target
  });
}

如果你的pdf项目更复杂,你可能需要添加更多的逻辑来找到正确的元素。

另一个选项是在选择器组件中呈现pdf项。然后,您可以直接向这些项添加侦听器。

最新更新