我想为setstate创建一个通用处理程序,而不要使用两个不同的处理程序?我怎样才能做到这一点?
我在想类似的东西:
setStateHandler= (stateToBeChanged) =>{
this.setState({
stateToBeChanged: !this.state.stateToBeChanged
});
}
handleHappyToggle = () =>{
this.setState({
Happy: !this.state.Happy
});
}
handleSadToggle = () => {
this.setState({
Sad: !this.state.Sad
});
}
我的两个可触摸的混浊:
<TouchableOpacity
onPress={this.handleHappyToggle}
>
<Text> {this.state.happy ? 'Yes' : 'No' } </Text>
</TouchableOpacity>
<TouchableOpacity
onPress={this.handleSadToggle}
>
<Text> {this.state.sad? 'Yes' : 'No' } </Text>
</TouchableOpacity>
答案 0 :(得分:2)
编辑: 添加了演示StackSnippet ...
编辑2: :总共添加了3种“一般”处理方式
您可以使用通用处理程序来完成此操作-只需提供“心情”作为参数即可。
handleMoodToggle = mood => event => {
if(!["Happy", "Sad"].includes(mood)){
return null;
}
this.setState({
[mood]: !this.state[mood]
})
}
<TouchableOpacity onPress={this.handleMoodToggle("Happy")}>
<Text> {this.state.happy ? 'Yes' : 'No'} </Text>
</TouchableOpacity>
<TouchableOpacity onPress={this.handleMoodToggle("Sad")}>
<Text> {this.state.sad ? 'Yes' : 'No'} </Text>
</TouchableOpacity>
演示:
const { Component } = React;
const { render } = ReactDOM;
class App extends Component {
state = {
Happy: true,
Sad: false
};
handleMoodToggle1 = mood => event => {
if (!["Happy", "Sad"].includes(mood)) {
return null;
}
this.setState({
[mood]: !this.state[mood]
})
};
handleMoodToggle2 = event => {
this.setState({
[event.target.innerHTML]: !this.state[event.target.innerHTML]
});
}
handleMoodToggle3 = event => {
this.setState({
[event.target.name]: !this.state[event.target.name]
});
}
render() {
return (
<div>
<button onClick={this.handleMoodToggle1("Happy")}>Toggle Happy</button>
<button onClick={this.handleMoodToggle1("Sad")}>Toggle Sad</button>
<br />
<button onClick={this.handleMoodToggle2}>Happy</button>
<button onClick={this.handleMoodToggle2}>Sad</button>
<br />
<button name="Happy" onClick={this.handleMoodToggle3}>Happy 3</button>
<button name="Sad" onClick={this.handleMoodToggle3}>Sad 3</button>
<pre>{JSON.stringify(this.state, null, 2)}</pre>
</div>
);
}
}
render(<App />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.9.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.9.0/umd/react-dom.production.min.js"></script>
答案 1 :(得分:1)
您可以为我检查一下我的礼物:
export default class App extends Component {
state = {
emotions: [
{ name: 'happy', status: true },
{ name: 'sad', status: false },
{ name: 'angry', status: true },
]
}
handleEmotionToggle = (index) => {
let emotions = [...this.state.emotions]
emotions[index].status = !emotions[index].status
this.setState({
emotions
})
}
render() {
return (
<View style={styles.container}>
{
this.state.emotions.map((emotion, index) => {
return (
<TouchableOpacity key={index}
onPress={()=>this.handleEmotionToggle(index)}
>
<Text style={{margin:10,fontSize:20}}>{emotion.name} - {emotion.status ? "YES":"NO"} </Text>
</TouchableOpacity>
)
})
}
</View>
);
}
}