2016-02-12 50 views
1

我有一个容器组件React - Redux:如何将它绑定到es6中的父容器?

import { AddQuest } from '../components/AddQuest.jsx' 
import { connect } from 'react-redux' 
import { addQuestActionCreator } from '../actions.js' 

const mapStateToProp = (
    dispatch, 
    ownProps 
) => { 
    return { 
    onClick:() => { 
     console.log(this);// <-- this represents the window object instead the AddQuest component 
     dispatch(addQuestActionCreator(this.input.value)); //<-- throws : Uncaught TypeError: Cannot read property 'value' of undefined 
     this.input.value = ''; 
    } 
    } 
} 

export const AddQuestContainer = connect(
    undefined, 
    mapStateToProp 
)(AddQuest); 

和表象的成分

import React from 'react' 
import { connect } from 'react-redux' 
import { addQuestActionCreator } from '../actions.js' 

export const AddQuest = ({onClick}) => { 
    let input; 

    return(

    <div> 
     <input type="text" ref={ 
     node =>{ 
      input = node; 
     } 
     }/> 
     <button onClick={onClick.bind(this)}>Add quest</button> 
    </div> 
) 
}; 

但每次我点击我的按钮来添加一个任务。我有这个错误Uncaught TypeError: Cannot read property 'value' of undefined.

我对bind(this)的理解有些问题。我认为这会将展示组件的参考传递给容器组件。

为什么不是这样?

+0

Redux的鼓励此类使用的本地状态的重写你的榜样。您可以将合成事件或提取的值传递给处理程序 - 很可能您的输入没有复杂的结构,它只是一个文本。在另一种情况下,您可以使用redux-form组件来处理这个问题。 –

回答

2

您可以通过参数传递价值,并在AddQuest复位输入

const mapStateToProp = (
    dispatch, 
    ownProps 
) => { 
    return { 
    onClick: (value) => { 
     dispatch(addQuestActionCreator(value)); 
    } 
    } 
} 

const AddQuest = ({ onClick }) => { 
    let input; 

    const send =() => { 
    onClick(input.value) 
    input.value = ''; 
    } 

    return (
    <div> 
     <input type="text" ref = { 
     (node) => { input = node } 
     } /> 
     <button onClick={ send }>Add quest</button> 
    </div> 
) 
}; 

Example

更新

arrow functions不会没有自己的this - 所以,如果你使用.bind(this)内部箭头功能this指的是父母的分数(在你的例子中它将是windowundefined如果使用strict mode),你可以用ES2015

class AddQuest extends React.Component { 
    render() { 
    return <div> 
     <input type="text" ref="text" /> 
     <button onClick={ this.props.onClick.bind(this) }>Add quest</button> 
    </div> 
    } 
} 

const mapStateToProp = (
    dispatch, 
    ownProps 
) => { 
    return { 
    onClick: function() { 
     // this refers to AddQuest Object 
     dispatch(addQuestActionCreator(this.refs.text.value)); 
     this.refs.text.value = ''; 
    } 
    } 
} 

Example

相关问题