【发布时间】:2019-04-18 17:17:26
【问题描述】:
我有一个“输出框”组件,并希望在单击按钮时更改组件中显示的文本。
我已经阅读了有关道具和状态的信息,但我似乎无法让它们按照我需要的方式工作。我刚开始 react-native 并且有丰富的 c++ 背景。我想我可以在“OutputBox”组件中声明一个变量“text”,然后调用“setOutputBoxText”函数并更改“text”变量。 Getter 和 Setter 范式。我只是想不通如何使用道具将参数“传递”给组件等。
export default class HelloWorldApp extends Component {
render() {
return (
<View style={{ flex: 1, alignItems: "flex-end" }}>
<CustomButton
text="N"
onPress={() => {
OutputBox.setOutputBox('You head North');
alert("You head North");
}}
/>
<OutputBox></OutputBox>
</View>
);
}
}
class CustomButton extends Component {
render() {
const { text, onPress} = this.props;
return (
<TouchableOpacity style={styles.buttonStyle}
onPress={() => onPress()}
>
<Text style={styles.textStyle}>{text}</Text>
</TouchableOpacity>
);
}
}
class OutputBox extends Component {
constructor( props ) {
super( props );
var displayText = 'Hello Traveller';
}
setOutputBox( newText ){
displayText = newText;
}
render() {
return (
<View style={ styles.outputBox }>
<Text>{this.displayText}</Text>
</View>
);
}
}
我希望能够做与我所拥有的类似的事情,但是我只是不断得到typeError: OutputBox.setOutputBox 不是一个函数。我知道这是 react-native 的错误范例。我似乎无法用道具和状态来做这样的事情。
更新:我不再收到错误 typeError: OutputBox.setOutputBox is not a function。现在,OutputBox 不显示任何内容。如何让OutputBox 的<Text/> 组件更改和显示。
【问题讨论】:
-
hmmm,如果我将
alert放入并将其设置为this.props.displayText,这似乎不会在OutputBox中显示任何内容,它会更改,但这仍然不起作用用于更改OutputText的文本。
标签: react-native