【问题标题】:React Native custom toggle button componentReact Native 自定义切换按钮组件
【发布时间】:2023-03-16 14:11:01
【问题描述】:

我一直在开发一个类似于单选按钮的自定义组件,但现在有一些关于如何扩展它的问题。

我希望能够通过样式表设置 TouchableOpacity 样式,由于它的动态特性,该样式表当前是内联的。

我还希望能够通过价格传递第二个变量/字符串。

如果我可以通过 2 个变量发送上述内容,这些变量将通过 firebase/props 发送,那么我将如何公开它们。

组件

import React, { Component } from 'react'
import { View, Text, TouchableOpacity } from 'react-native'
import styles from './Styles/OptionStyle'

export default class Option extends Component {
  constructor(props) {
    super(props);
    this.state = {
      activeOption: this.props.options[0],
    };
  }
  updateActiveOption = (activeOption) => {
    this.setState({
      activeOption,
    });
  };
  render() {
    return (
      <View style={styles.container}>
        {this.props.options.map((option, index) => (
          <TouchableOpacity key={index} style={styles.button}
            onPress={() => {
              this.props.onChange(option);
              this.updateActiveOption(option);
            }}
          >
            <Text
              style={{
                width: 100,
                borderWidth: 1,
                borderColor: this.state.activeOption === option ? '#4caf50' : 'rgb(117, 117, 118)',
                borderRadius: 6,
                height: 100,
                padding: 10,
                color: this.state.activeOption === option ? '#4caf50' : 'rgb(117, 117, 118)'
              }}
            >
              {option}
            </Text>
          </TouchableOpacity>
        ))}
      </View>
    );
  }
}

调用组件

<Option
            options={['Small','Medium','Large']}
            onChange={(option) => {
              console.log(option);
            }}
          />

这是我希望能够为每个选项传递 2 个变量的地方,即 Small 和 $3.95 或 Medium 和 $4.95

【问题讨论】:

    标签: react-native radio-button components toggle custom-controls


    【解决方案1】:

    您可以通过 props 传递对象数组,然后在组件中使用它们。像这样的:

    <Option
            options={[{label: 'Small', price: '$3.95'},{label: 'Medium', price: '$4.95'}]}
            onChange={(option) => {
              console.log(option);
            }}
          />
    

    然后在您的组件中简单地迭代它,例如使用 map:

    {this.props.options.map((option, index) => (
     <TouchableOpacity><Text>{option.label} - {option.value}</Text></TouchableOpacity>
    ))}
    

    【讨论】:

    • 我更想弄清楚如何使用 this.props.data.options 设置 options={ 如果可能的话。谢谢
    • 我仍然不知道我是否理解问题所在,但您可能只是想传递道具。这可以通过多种方式完成,例如:
    • 我的意思是我可以做
    猜你喜欢
    • 2018-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-15
    • 2018-08-05
    • 2011-03-31
    • 2015-03-31
    • 1970-01-01
    相关资源
    最近更新 更多