我开始学习React Native,对于我的项目,我创建了一个简单的Button组件,可以在我的项目中重用.我根据变量’disabled’动态设置不透明度值,但是,按钮的外观不会随着opacity变量的值而变化.我四处搜寻,但我没有找到解释..
任何帮助将不胜感激.
任何帮助将不胜感激.
这是我的源代码:
import React from 'react' import { View,Text,TouchableOpacity,StyleSheet } from 'react-native' import PropTypes from 'prop-types' //TODO: arrumar o problema com a opacidade export default function Button({text,onPress,style,disabled,textStyle}) { let opacity = disabled === true ? 0.5 : 1 // console.log('opacity',opacity) return ( <TouchableOpacity onPress={onPress} style={[defaultStyles.button,{opacity: opacity}]} disabled={disabled}> <Text style={[defaultStyles.text,textStyle]}>{text}</Text> </TouchableOpacity> ) } const defaultStyles = StyleSheet.create({ text: { color: 'white' },button: { backgroundColor: 'black',margin: 15,padding: 15,borderRadius: 10 },}) Button.propTypes = { text: PropTypes.string,onPress: PropTypes.func,style: PropTypes.oneOfType([ PropTypes.string,PropTypes.array,PropTypes.object ]),disabled: PropTypes.bool,textStyle: PropTypes.oneOfType([ PropTypes.string,PropTypes.object ]) }
class NewDeck extends Component { state={ title: null } submit = () => { const { add,goBack } = this.props let deck = {...this.state} if(!deck['deckId']){ deck['deckId'] = Date.now() deck['logs'] = [] } !deck['cardsId'] && (deck['cardsId'] = []) add(deck).then(() => { this.props.navigation.navigate('Deck',{deckId: deck.deckId,title: deck.title}) this.setState({title: null}) } ) } render(){ const disabled = this.state.title === null || this.state.title.length === 0 return ( <KeyboardAwareScrollView resetScrollToCoords={{ x: 0,y: 0 }} contentContainerStyle={styles.container}> <Text style={textStyles.title2}>Whats the title of your deck?</Text> <TextInput editable={true} style={[styles.input,textStyles.body]} placeholder='Type title here' maxLength={25} value={this.state.title} onChangeText={(text) => { this.setState({title: text}) }} /> <Button onPress={this.submit} text='Submit' style={{backgroundColor: colors.pink}} textStyle={textStyles.body} disabled={!this.state.title} /> </KeyboardAwareScrollView> ) } }
如果newDeck组件的标题为空或null,则disabled变量为true.当此变量为true时,按钮的不透明度应仅为0.5.当值变为false时,不透明度再次变为1.如果我在组件中记录不透明度的值,我可以看到它从0.5到1,但组件的外观不会改变.
解决方法
不确定它是否是TouchableOpacity组件上的错误,但在单击组件之前,不透明度不会在重新渲染时更新
修复你的问题只需在视图中包含可触摸的内容并将不透明度应用于视图而不是可触摸
export default function Button({text,textStyle}) { const opacity = disabled === true ? 0.5 : 1 // console.log('opacity',opacity) return ( <TouchableOpacity onPress={onPress} disabled={disabled} style={[defaultStyles.button,style]}> <View style={{opacity}}> <Text style={[defaultStyles.text,textStyle]}>{text}</Text> </View> </TouchableOpacity> ) }