在更改事件上绑定文本输入值 - React Native + Redux

时间:2018-02-09 14:10:35

标签: javascript forms reactjs redux

我在React Native和Redux中创建表单。我添加了TextInput并希望在Reducer中更改此字段的状态。我遇到了麻烦,因为我不知道如何将(change) => this.setState({change})函数添加到我的Redux架构中。我使用了combine reducers,并且不知道如何绑定该值。 简而言之,我需要在更改函数上获得TextInput的默认行为,但我必须使用Redux来执行此操作。

Form.js

const mapDispatchToProps = dispatch => {
  return {
      changeNameInput: () => dispatch({type: 'CHANGE_NAME_INPUT'})
  };
};

const mapStateToProps = state => {
  return {
      change: state.changeNameInput.change
  };
};

class Form extends React.Component {
  render() {
    return (
      <View>
         <FormLabel>Name</FormLabel>
         <TextInput
            onChangeText={this.props.changeNameInput}
            value={this.props.change}
        />
      </View>
    );
  }
}

Reducer.js

const initialState = {
    change: 'Your name'
   };

   const changeinputReducer = (state = initialState, action) => {
     switch (action.type) { 
       case 'CHANGE_NAME_INPUT':

  //Problem

         return {...state, change: '????' };
        default:
         return state;
     }
   };

   export default changeinputReducer;

1 个答案:

答案 0 :(得分:4)

要将值从TextInput传递给reducer,您需要更改调度函数:

const mapDispatchToProps = dispatch => {
  return {
      changeNameInput: (text) => dispatch({type: 'CHANGE_NAME_INPUT', text})
  };
};

并在您的reducer中将其更改为

const changeinputReducer = (state = initialState, action) => {
     switch (action.type) { 
       case 'CHANGE_NAME_INPUT':

  //Solution

         return {...state, change: action.text };
        default:
         return state;
     }
   };

希望它有效..