嗨,我想将TouchableOpacity包裹在Text中,因为我想使某些文本可点击。当我将所有内容包装在Text中时,它看起来很完美,这就是我想要的外观。
<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角度看,它们未正确对齐。
这是仅在Text上显示的屏幕快照,其中TouchableOpacity不起作用,第二位在View中,其中TouchableOpacity可以起作用,但看起来不正确。
如何使它看起来像正确的第一位。任何建议,不胜感激。
谢谢R
您可以嵌套Text元素,并在要使其可按下的每个嵌套Text元素上分配onPress处理程序(链接)。
见下文。有一个外部文本元素,内部有另一个文本元素,子文本元素有一个onPress处理程序,如果运行它,您将看到“但这是!”。按下时执行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>
您可以设置样式,使其放置在具有/ a onPress处理函数的任何Text元素上,以使其具有不同的颜色,如示例图像中所示。
注意,这很像HTML,例如,您将在ap元素内嵌套锚标记。
<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,示例文本格式不是很好。