Output events's Angular in ReactJs

丶灬走出姿态 提交于 2020-01-02 10:17:33

问题


I was looking the way to create in ReactJs similar output events like Angular.

I am making a library of components in ReactJs according to Atomic design, so, I have, for example, a Button injected in other component, and I would like to know how I could write a props for Button, so everytime the user press the button would launch this prop(a output in Angular way) to be detected in the parent where it was injected.

I don't want to use the State because I want that the components are fully independent.

Thanks in advance


回答1:


There is no equivalent to @output EventEmitterin react. The standard way to do this is to pass a callback in the props to the child component. Like so:

  class Parent extends React.Component {
      handleChildClicked = () => {
          console.log('child clicked');
      }
      render() {
        <Child onClick={this.handleChildClicked} />
      }
  }

  const Child = (props: Props) => {
    const { onClick } = props;
    return (
      <button onClick={onClick}>Clicky!</button>
    );
  };


来源:https://stackoverflow.com/questions/48357283/output-eventss-angular-in-reactjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!