首页 > 解决方案 > Reactjs - 如何将字体真棒图标附加到 ref

问题描述

我正在尝试使用 appendChild 将 fontawesome 图标添加到 react 中的 ref。我得到错误:

无法在“节点”上执行“附加孩子”:参数 1 不是“节点”类型。

使用 append 而不是 appendChild 只能添加文本。

类示例扩展 React.Component {

handle = (e) => {
    e.target.appendChild('<i className="fas fa-minus-circle"/>')
}

render() {
    return (
        <div className="container">
            <button onClick={this.handle}>CLICK HERE</button>
        </div>
    )
}

}

标签: reactjs

解决方案


考虑稍微改变你的方法。您可以使用下面的代码实现您期望的相同结果,并且在 React 中使用状态和条件 JSX 更为常见:

class Example extends React.Component {
  state = { images: [] }

  handle = () => {
    this.setState({ images: [...images, 'fas fa-minus-circle'] });
  }

  render() {
    return (
      <div className="container">
        <button onClick={this.handle}>CLICK HERE</button>
        {this.state.images.map((image, index) => {
          <i key={index} className={image} />
        })}
      </div>
    );
  }
}

推荐阅读