带参数React的事件处理程序

时间:2016-04-18 12:27:39

标签: reactjs

我有两个按钮(图标)。根据我单击哪个(参数),应调用一个函数来更改我的视图布局。

export default class ToolbarPictograms extends Component {
      static propTypes = {
        layout: PropTypes.string.isRequired,
        changeLayout: PropTypes.func.isRequired
      }

      constructor(props) {
        super(props)
        this.handleClick = this.handleClick.bind(this)
      }

      handleClick = value => {
        this.props.changeLayout(value)
      }

      render() {
        const changeLayout = this.props.changeLayout
        return (
          <div style={style.container}>
            <Divider />
            <div className='row end-xs'>
              <ViewListIcon onClick={() => changeLayout('list')} />
              <ViewModuleIcon onClick={() => changeLayout('modules')}/>
            </div>
            <Divider />
          </div>
        )
      }
    }

目前我使用箭头功能,它有效,但我有一个警告: JSX道具不应使用箭头功能

在React中做这样的事情的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

建议的方法是将对函数的引用作为子组件的属性传递,然后让子组件使用所需的参数调用该函数。这样做的原因是,在渲染过程中创建函数可能会由于垃圾收集器活动的增加而导致性能问题。

因此,您可以将功能更改为

render() {
        const changeLayout = this.props.changeLayout
        return (
          <div style={style.container}>
            <Divider />
            <div className='row end-xs'>
              <ViewListIcon onClick={this.props.changeLayout} />
              <ViewModuleIcon onClick={this.props.changeLayout}/>
            </div>
            <Divider />
          </div>
        )
      }

然后,在ViewListIcon和ViewModuleIcon中,使用适当的参数调用回调。这些可以硬编码或作为更多道具传递。