提问人:BRDroid 提问时间:9/4/2018 最后编辑:David SchumannBRDroid 更新时间:12/18/2018 访问量:14568
如何在 Text ReactNative 中包含 TouchableOpacity
How to include TouchableOpacity within Text ReactNative
问:
嗨,我想将 TouchableOpacity 包装在文本中,因为我想让一些文本可点击。当我将所有内容包装在文本中时,它看起来很完美,这就是我想要的外观。
<Text
style={{color: colors.black,
fontSize: 12,
fontWeight: 'normal',
marginTop: 10,
lineHeight: 18}}>
{strings.loginPrivacyTermsCondOne}
<Text style={{color: colors.primaryColor,
fontSize: 12,
fontWeight: 'normal',}}>
{strings.loginPrivacyTermsCondTwo}
</Text>
{strings.loginPrivacyTermsCondThree}
<Text style={{color: colors.primaryColor,
fontSize: 12,
fontWeight: 'normal'}}>
{strings.loginPrivacyTermsCondFour}
</Text>
{/* <TouchableOpacity onPress={ this.termsOfService }>
<Text style={{color: colors.primaryColor,
fontSize: 12,
fontWeight: 'normal',}}>
{strings.loginPrivacyTermsCondFour}
</Text>
</TouchableOpacity> */}
</Text>
当我添加 TouchableOpacity 时,它不起作用。
我尝试在视图中添加它,然后它工作正常,并且我能够添加 TouchableOpacity,但从 UI 的角度来看,它们没有正确对齐。
这是仅显示文本的屏幕截图,其中 TouchableOpacity 不起作用,第二个位位于视图中,其中 TouchableOpacity 可以工作但看起来不正确。
如何让它看起来像第一位。任何建议非常感谢。
谢谢 R
答:
您可以嵌套 Text 元素,并在要使其可压的每个嵌套 Text 元素(链接)上分配 onPress 处理程序。
见下文。有一个外部文本元素,里面是另一个文本元素,子文本元素有一个 onPress 处理程序,如果你运行这个,你会看到 'But this is!' 当你按下它时执行 onPress 处理程序,不需要 Touchable* 元素。
<Text style={{color: '#000'}}>
This part is not clickable
<Text onPress={() =>
{alert('but this is');}}
style={{color: '#00F'}}>
But this is!
</Text>
but this isn't
</Text>
您可以创建一个样式以放置在任何具有 onPress 处理程序的 Text 元素上,使它们具有不同的颜色,如示例图像所示。
请注意,这很像 HTML,例如,您将锚标记嵌套在 p 元素中;
<p>
This part is not clickable
<a href="https://google.com"> but this is</a>
but this isn't
</p>
在您的示例中,它会是这样的(未经测试):
<Text style={{color: colors.black,
fontSize: 12,
fontWeight: 'normal',
marginTop: 10,
lineHeight: 18}}>
{strings.loginPrivacyTermsCondOne}
<Text style={{color: colors.primaryColor,
fontSize: 12,
fontWeight: 'normal',}}>
{strings.loginPrivacyTermsCondTwo}
</Text>
{strings.loginPrivacyTermsCondThree}
<Text style={{color: colors.primaryColor,
fontSize: 12,
fontWeight: 'normal'}}>
{strings.loginPrivacyTermsCondFour}
</Text>
<Text onPress={ this.termsOfService }
style={{color: colors.primaryColor,
fontSize: 12,
fontWeight: 'normal'}}>
{strings.loginPrivacyTermsCondFour}
</Text>
</Text>
为了回应您的评论,这里有一个在点击链接后更改颜色的敲门示例。
简而言之,我在状态上添加了一个布尔字段,一旦文本被按下,我将该状态变量更新为 true,然后文本元素的样式值有一个三元运算符,它决定以哪种颜色呈现文本,在我的示例中,如果尚未按下,它将显示为“colors.primaryColor”,一旦它被按下,它将显示为“红色”。
class Foo extends Component {
constructor (props) {
super(props);
this.state = {
privacyClicked: false //Track if they have clicked privacy
};
}
render () {
return (
<Text onPress={ () =>{
this.setState({
privacyClicked: true
});
}} style={{color: (this.state.privacyClicked ? colors.primaryColor : 'red'),
fontSize: 12,
fontWeight: 'normal'}}>
{strings.loginPrivacyTermsCondFour}
</Text>
);
}
}
PS,示例文本的格式不是很好。
评论