反应 onclick 数据值返回 null

Phi*_*ppe 6 javascript reactjs

我正在尝试将我的状态对齐更改为:左对齐、居中对齐、右对齐或对齐,具体取决于<Icon />我单击的对齐方式。但是,e.target.getAttribute('data-value')正在返回null

当我更改<Icon icon="align-left" />by 时left,它正在工作。e.target.getAttribute('data-value')正在返回数据值。

所以,我怎样才能改变我的状态,以左,右中心或我的点击自圆其说<Icon />

class TextStyleParams extends React.Component {
  constructor(props) {
    super(props);
    this.onClickAlignment = this.onClickAlignment.bind(this);

    this.state = {
      textStyle: {
        alignment: 'left',
        ...,
      },
    };
  }

  onClickAlignment(e) {
    const { textStyle } = this.state;
    const newTextStyle = {
      ...textStyle,
      alignment: e.target.getAttribute('data-value'),
    };
    this.setState({ textStyle: newTextStyle });
    this.props.updateTextStyle(newTextStyle);
  }
    
  render() {
    const { textStyle } = this.state;
        
    return (
      <div>
        <span role="button" onClick={this.onClickAlignment} data-value="left"><Icon icon="align-left" /></span>
        <span role="button" onClick={this.onClickAlignment} data-value="center"><Icon icon="align-center" /></span>
        <span role="button" onClick={this.onClickAlignment} data-value="right"><Icon icon="align-right" /></span>
        <span role="button" onClick={this.onClickAlignement} data-value="justify"><Icon icon="align-justify" /></span>
      </div>
    );
  }
}

class Icon extends React.Component {
  render() {
    const { icon } = this.props;
    return (
      <svg viewBox="0 0 24 24" styleName="icon" className={`icon-${icon}`}>
        <use xlinkHref={`iconset.svg#${icon}`} />
      </svg>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

Obl*_*sys 11

尝试使用e.currentTarget.getAttribute('data-value'). 该target属性指的是事件起源于的 dom 元素(将是svg元素),而currentTarget指的是处理程序附加到的元素。