从React中的子级调用函数

时间:2019-05-20 08:40:23

标签: javascript reactjs

假设我有这个组件

class Foo extends React.Component {
    onClick = () => {
        alert('Yay');
        this.props.setWhatever()
    }

    render() {
        return (
            <Bar>
                <input 
                    type='radio'
                    checked={this.props.getWhatever}
                    onClick={() => this.onClick()} />
            </Bar>
        )
    }
}


class Bar extends React.Component {    
    render() {
        return (
            <label>
               {this.props.children}
            </label>
        )
    }
}

this.onClick()未执行。当我将onClick={() => this.onClick()}更改为onClick={this.onClick()}时,它可以工作,但会以无限循环结束。为什么会这样?

3 个答案:

答案 0 :(得分:2)

通过将<input />元素的onClick属性设置为onClick={this.onClick()},这将导致{{1}每次调用onClick中定义的Foo函数}}元素被渲染。

调用Foo的<input />将依次调用onClick,据我所知,这会导致this.props.setWhatever()组件重新呈现。重新渲染Foo组件会触发该循环再次重复,从而引起您注意到的无休止的循环行为。

通过将<Foo/>道具设置为onClick,您(在本地)声明了一个箭头函数,并将其传递给onClick={() => this.onClick()}道具(而不是像详细说明的那样立即调用它)以上)。

使用这种“箭头函数方法”,当单击输入元素时,该事件将触发您定义并传递给onClick道具的函数,该函数被称为该用户事件的副作用。

希望能澄清一些事情:-)

更新

有几种方法可以从onClick处理程序中传递额外的参数。一种简单的方法是:

onClick

然后更新您的组件{/* Inside render() */} <input type='radio' checked={this.props.getWhatever} onClick={(event) => this.onClick(event, 'some', 'other', 'arguments')} /> 方法:

onClick

答案 1 :(得分:1)

箭头函数表达式不适合用作方法,并且不能用作构造函数。 箭头函数会自动将this绑定到父/外部组件或定义/执行函数的上下文。

  • onClick={() => this.onClick()}-点击发生时this
    实际上是指输入按钮,而不是您的组件。

  • onClick={this.onClick()}-在呈现组件后立即创建并执行闭包。

  • onClick={this.onClick}-当点击发生时,将创建并执行闭包。

请在构造函数中绑定所有函数,并避免使用箭头函数。

constructor(props){this.onClick = this.onClick.bind(this)}
...
onClick() {...}
...
<input onClick={this.onClick} />

请在此处https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

详细了解箭头功能

更新: 在您想在箭头功能内使用this的地方避免使用箭头功能。

答案 2 :(得分:0)

在为onChange使用checked属性时,应始终使用radio type input事件。就您而言,您可能会遇到警告。

Warning: Failed prop type: You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`. 

在您的Foo组件中,

<input
  type="radio"
  checked={this.props.getWhatever}
  onChange={this.onClick.bind(this)} //Bind "this" here or in contructor or use arrow function as you are using 
/>

工作Demo