Javascript React native-如何在多个按钮上应用道具
我有一个按钮,当我切换按钮时,它会改变颜色。 代码如下:Javascript React native-如何在多个按钮上应用道具,javascript,reactjs,react-native,redux,Javascript,Reactjs,React Native,Redux,我有一个按钮,当我切换按钮时,它会改变颜色。 代码如下: state={ status:[ {toggle:false} ] } _onPress(){ const newState = !this.state.toggle this.setState({toggle:newState}) } render(){ const {toggle} = this.state const textValue = toggle?"ON":"OFF"
state={
status:[
{toggle:false}
]
}
_onPress(){
const newState = !this.state.toggle
this.setState({toggle:newState})
}
render(){
const {toggle} = this.state
const textValue = toggle?"ON":"OFF"
const buttonBG = toggle?"#6AAAC6":"white"
const textColor = toggle?"white":"gray"
return(
<TouchableOpacity
onPress={()=>this._onPress()}
<Text>button</Text>
</TouchableOpacity>
)
}
}
状态={
地位:[
{toggle:false}
]
}
_onPress(){
const newState=!this.state.toggle
this.setState({toggle:newState})
}
render(){
const{toggle}=this.state
const textValue=切换“开”:“关”
const buttonBG=切换?#6AAAC6:“白色”
const textColor=切换“白色”:“灰色”
返回(
这是.\u onPress()}
按钮
)
}
}
但是如果我有多个按钮,它们基本上都有相同的功能呢。有没有一种方法可以重复使用此代码而无需多次复制和粘贴?您可以创建组件调用
CustomButton
class CustomButton extends React.Component {
static defaultProps = {
onToggle: () => {},
}
state = {
status: [{ toggle: false }]
}
_onPress() {
const newState = !this.state.toggle
this.setState({ toggle: newState })
this.props.onToggle(newState)
}
render() {
const { toggle } = this.state
const textValue = toggle ? 'ON' : 'OFF'
const buttonBG = toggle ? '#6AAAC6' : 'white'
const textColor = toggle ? 'white' : 'gray'
return (
<TouchableOpacity onPress={() => this._onPress()}>
<Text>button</Text>
</TouchableOpacity>
)
}
}
class CustomButton扩展了React.Component{
静态defaultProps={
onToggle:()=>{},
}
状态={
状态:[{toggle:false}]
}
_onPress(){
const newState=!this.state.toggle
this.setState({toggle:newState})
这个.props.onToggle(newState)
}
render(){
const{toggle}=this.state
const textValue=切换“开”:“关”
const buttonBG=切换?#6AAAC6':“白色”
const textColor=切换“白色”:“灰色”
返回(
这个。_onPress()}>
按钮
)
}
}
可以在任何你想要的地方使用
class App extends React.Component {
onButtonToggle = (isToggle) => {
console.log(isToggle)
}
render() {
return (
<View>
<CustomButton onToggle={this.onButtonToggle} />
</View>
)
}
}
类应用程序扩展了React.Component{
onButtonToggle=(isToggle)=>{
console.log(isToggle)
}
render(){
返回(
)
}
}
我想我做错了什么。我收到一个错误“找不到变量:callbackfortoggle”。代码中的“callBackForToggle”在哪里?callBackForToggle
只是函数的名称。当CustomButton是toggle时,它用于你想做的事情。我是一个新的本地人。如果你能给我举个例子,我将不胜感激。