2017-08-03 65 views
0

我正在編寫一個用react-redux編寫的項目。我想將處理程序傳遞給子組件,以便可以從子組件觸發處理程序。
我父組件代碼如何在react-redux中傳遞處理程序

import React from 'react'; 
import Input from 'src/containers/Input'; 

export default class AddChannelComponent extends React.Component<void, PropsType, void> { 
    render() {  
     function inputHandler (value){ 
      console.log("value is",value); 
     } 

    return (
     <div > 
      <p>Type your input</p> 
      <div> 
      <Input inputHandler={this.inputHandler} placeholder="Search all public channels..." /> 
      </div> 
     </div> 
    ); 
    } 
} 

輸入是一個js文件,該文件調用組件InputComponent.js
代碼Input.js文件是:

import { connect } from 'react-redux'; 
import InputComponent from 'src/components/InputComponent'; 

const mapStateToProps = (state) => ({ 
}); 

const mapDispatchToProps = (dispatch) => ({ 
}); 

const Input = connect(
    mapStateToProps, 
    mapDispatchToProps 
)(InputComponent); 

export default Input; 

現在我InputComponent.js文件的代碼:

import React from 'react'; 


export default class InputComponent extends React.Component<void, PropsType, void> { 
    callHandler = event => { 
      console.log("value in input",event.target.value); 
      this.props.inputHandler(event.target.value) <== Error Occur 
    } 
    render() { 
    return (
     <input {...this.props} onChange={this.callHandler}/> 
    ); 
    } 
} 

this.props.inputHandler(event.target.value)給了我錯誤_this.props.inputHandler我這不是一個功能。如何在子組件中調用父處理程序。
在此先感謝。

回答

1
inputHandler = (value) => { 
     console.log("value is",value); 
    }  
    render() {  
    ...... 

代替

render() {  
    function inputHandler (value){ 
     console.log("value is",value); 
    } 
    ...... 

寫在AddChannelComponent類的範圍inputHandler功能,然後使用​​

如果你正在使用閉合功能(在你的情況下)直接inputHandler使用作爲

<Input inputHandler={inputHandler} placeholder="Search all public channels..." /> 
1

Just你有沒有試圖將你的inputHandler fn定義爲類方法? 您嘗試通過​​來訪問它,但是fn是在render方法中定義的。

0

你應該捆綁你的方法,根據React Docs

你必須要小心的這JSX回調的意思。在JavaScript中,類方法默認沒有綁定。如果您忘記綁定this.handleClick並將其傳遞給onClick,則在實際調用該函數時,這將是未定義的。

這不是特定於行爲的行爲;它是JavaScript中如何使用函數的一部分。一般來說,如果你在它後面引用一個沒有()的方法,比如onClick = {this.handleClick},你應該綁定該方法。

如果調用綁定讓你感到困擾,有兩種方法可以解決這個問題。如果您使用的是實驗性質的初始化程序語法,你可以使用屬性初始化到正確綁定回調

所以,在你的榜樣:

import React from 'react'; 


export default class InputComponent extends React.Component<void, PropsType, void> { 
    callHandler = event => { 
      console.log("value in input",event.target.value); 
      this.props.inputHandler(event.target.value) <== Error Occur 
    } 
    render() { 
    return (
     <input {...this.props} onChange={this.callHandler.bind(this)}/> 
    ); 
    } 
} 
相關問題