示例项目:https://snack.expo.io/SyyO8XxbZ
我正在尝试在TouchableOpacity组件中创建文本中心,我曾尝试使用lineHeight:50但我只是不想手动设置它。此外,我还尝试使用flex:1和justifyContent:' center'在容器中,但它只是搞砸了我的预期布局。
请帮忙!
import React, { Component } from 'react';
import { Text, View, TouchableOpacity} from 'react-native';
class Option extends Component {
constructor(props) {
super(props);
this.state = {
activeOption: this.props.options[0],
};
}
updateActiveOption = (activeOption) => {
this.setState({
activeOption,
});
};
render() {
return (
<View
style={{
flex: 1,
justifyContent: 'center',
flexDirection: 'row',
flexWrap: 'wrap',
marginTop:100
}}
>
{this.props.options.map((option) => (
<TouchableOpacity
style={{
margin: 5,
borderRadius: 5,
backgroundColor: this.state.activeOption === option ? 'lightgrey' : 'white',
borderWidth: 1,
borderColor: this.state.activeOption === option ? 'grey' : 'lightgrey',
overflow: 'hidden',
justifyContent: 'center',//can't work
}}
onPress={() => {
this.props.onChange(option);
this.updateActiveOption(option);
}}
>
<Text
style={{
//lineHeight: 50,
textAlign: 'center',
width: 150,
height: 50,
color: 'black',
}}
>
{option}
</Text>
</TouchableOpacity>
))}
</View>
);
}
}
export default class App extends Component {
render() {
return (
< Option
options={['A', 'B', 'C', 'D']}
onChange={(option) => {
console.log(option);
}}/>
);
}
}
答案 0 :(得分:1)
import React, { Component } from 'react';
import { Text, View, TouchableOpacity} from 'react-native';
class Option extends Component {
constructor(props) {
super(props);
this.state = {
activeOption: this.props.options[0],
};
}
updateActiveOption = (activeOption) => {
this.setState({
activeOption,
});
};
render() {
return (
<View
style={{
flex: 1,
justifyContent: 'center',
flexDirection: 'row',
flexWrap: 'wrap',
marginTop:100
}}
>
{this.props.options.map((option) => (
<TouchableOpacity
style={{
margin: 5,
borderRadius: 5,
backgroundColor: this.state.activeOption === option ? 'lightgrey' : 'white',
borderWidth: 1,
borderColor: this.state.activeOption === option ? 'grey' : 'lightgrey',
overflow: 'hidden',
height: 50,
justifyContent: 'center',
}}
onPress={() => {
this.props.onChange(option);
this.updateActiveOption(option);
}}
>
<Text
style={{
//lineHeight: 50,
textAlign: 'center',
width: 150,
color: 'black',
}}
>
{option}
</Text>
</TouchableOpacity>
))}
</View>
);
}
}
export default class App extends Component {
render() {
return (
< Option
options={['A', 'B', 'C', 'D']}
onChange={(option) => {
console.log(option);
}}/>
);
}
}