【问题标题】:Passing a function to child component in reactjs将函数传递给reactjs中的子组件
【发布时间】:2017-11-18 10:24:37
【问题描述】:

这是我正在尝试做的一个简化示例。我想要做的是通过 props 将函数传递给 React 的不同组件。我可以将文本传递给道具,并通过 <button onClick={popup}> 直接调用该函数,但这不是我实验的目的。 onClick 不会触发该功能,并且在渲染时 console.log 中存在“未捕获”错误,这无济于事。

const Elem = (props) =>{ 
  return (<div>
    <h1> hi {props.name} {props.last} phase two </h1>
    <button onClick={props.clickon}> {props.text} </button>
      </div>
  );
};

function popup(){  
  alert("It works!")
}

class App extends React.Component{
  constructor(props) {
   super(props);
 }
  render(){return (<Elem name = 'paul' last='shreeman' clickon='popup' text='PushMe'/>
  )
}}

ReactDOM.render(
<App />, document.getElementById('root'))

这里是 codepen 的链接:https://codepen.io/pkshreeman/pen/GENmaG?editors=0010

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    原因是,你没有传递function,你传递的是一个字符串,要传递一个function,你需要这样写:

    clickon = {popup}
    

    现在它将通过function popup,而不是string "popup"

    完整代码:

    class App extends React.Component{
        constructor(props) {
           super(props);
        }
    
        render(){
             return (
                 <Elem name='paul' last='shreeman' clickon={popup} text='PushMe'/>
             )
        }
    }
    

    查看工作代码:https://codepen.io/anon/pen/MobvqB?editors=0010

    查看此答案以了解有关{}的含义的详细信息:

    What do curly braces mean in JSX (React)?

    【讨论】:

      猜你喜欢
      • 2018-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-02
      • 2017-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多