我在 React Native 和 Redux 中创建表单。我添加了 TextInput
并想在 Reducer 中更改此字段的状态。我遇到了麻烦,因为我不知道如何将 (change) => this.setState({change})
函数添加到我的 Redux 架构中。我使用 combine reducers 并且不知道如何绑定(bind)该值。
简而言之,我需要在更改函数时获得 TextInput
的默认行为,但我必须使用 Redux 来完成它。
表单.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;
最佳答案
为了将值从 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;
}
};
希望它有用..
关于javascript - 在更改事件上绑定(bind)文本输入值 - React Native + Redux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48707765/