React Native-如何在多个按钮上应用道具

时间:2018-07-27 02:49:20

标签: 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"
      const buttonBG = toggle?"#6AAAC6":"white"
      const textColor = toggle?"white":"gray"

return(
<TouchableOpacity
onPress={()=>this._onPress()}
<Text>button</Text>
</TouchableOpacity>
)
}
}

但是,如果我有多个按钮并且它们基本上执行相同的功能,该怎么办?有没有一种方法可以重用这段代码而无需多次复制和粘贴?

1 个答案:

答案 0 :(得分:3)

您可以创建组件调用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 App extends React.Component {

  onButtonToggle = (isToggle) => {
    console.log(isToggle)
  }

  render() {
    return (
      <View>
        <CustomButton onToggle={this.onButtonToggle} />
      </View>
    )
  }
}