[英]How to render a JSX component from the function show that it dispaly on screen
How to render JSX component from function to show it in the Screen. 如何从功能渲染JSX组件以在屏幕上显示它。
This below is the code which is not rendering the function JSX component... 以下是未呈现功能JSX组件的代码...
export default class HomeScreen extends Component{
state = {
isVisible:false
}
modal = ()=>{
return(<Text>Hello world</Text>);
}
render(){
return(
<View>
<Button onPress={this.setState({isVisible:true})}>Click me</Button>
{this.state.isVisible?this.modal:null}
</View>
);
}
}
And this Below code is working properly so i want to know what is error in first one. 而且下面的这段代码正常工作,所以我想知道第一个错误是什么。
export default class HomeScreen extends Component{
state = {
isVisible:false
}
modal = ()=>{
return(<Text>Hello world</Text>);
}
render(){
return(
<View>
<Button onPress={this.setState({isVisible:true})}>Click me</Button>
{this.state.isVisible?<Text>Hello world</Text>:null}
</View>
);
}
}
So Please tell me the error in first one what is problem due to which hello world text is not rendering through the JSX component return from the function modal. 因此,请告诉我第一个错误是什么问题,这是由于未通过功能模态返回的JSX组件呈现的Hello World文本。
Because you never called this.modal
You have to call it. 因为您从未调用过
this.modal
,所以必须调用它。 this.modal()
It's a function that needs to be invoked. this.modal()
这是一个需要调用的函数。 No Problem it happens.😁 没问题。😁
First problem is that you dont execute the modal function. 第一个问题是您不执行模态函数。
Second you invoke the function onPress
and doesn't pass a reference to a function, wrap it inside an arrow function
onPress={() => this.setState({ isVisible: true })}
其次,您调用函数
onPress
并没有传递对该函数的引用,而是将其包装在arrow function
onPress={() => this.setState({ isVisible: true })}
I will suggest to extract the Modal
to a new component and include it only when state.isVisible
is true
我建议将
Modal
提取到新组件,并仅在state.isVisible
为true
时包括它
const Modal = () => <h3>Modal</h3>;
export default class HomeScreen extends Component {
state = {
isVisible: false
}
render() {
return (
<View>
<Button onPress={() => this.setState({ isVisible: true })}>Click me</Button>
{this.state.isVisible && <Modal />}
</View>
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.