[英]Access Class Instance Props in React Component?
我有一个只返回孩子的班级
class Name extends PureComponent {
constructor(props) {
super(props);
this.text = "meow";
}
render() {
return this.props.children;
}
}
我在我的 JSX 中创建了组件,其中的文字是我的 Classes Prop “text”
<Name>
<Text>{Name.text}</Text>
</Name>
但是它错误地说 Name.text 不存在,您是要访问静态属性吗?
我如何使用 JSX 标签来执行new Name()
然后使用 React/React Native 访问里面的信息?
编辑 1 个更好的例子
interface User {
data: object;
firstName: string;
lastName: string;
}
class User extends PureComponent {
constructor(props: object) {
super(props);
fetch("https://randomuser.me/api/")
.then((response) => response.json())
.then((data) => this.data);
this.firstName = this.data.results.name.first;
this.lastName = this.data.results.name.last;
}
render() {
return this.props.children;
}
}
<User>
<Text>{User.firstName}</Text>
</User>
如果您希望User
组件具有计算名字和姓氏的逻辑,但您希望父组件决定如何处理这些值,那么我建议使用render prop 。 这让您可以将一个函数传递给Name
,告诉它您想要呈现什么。
这是一个将函数作为children
属性传递的示例(尽管您可以根据需要使用其他属性):
class User extends PureComponent {
state = {
firstName: '',
lastName: '',
}
constructor(props: object) {
super(props);
fetch("https://randomuser.me/api/")
.then((response) => response.json())
.then((data) => {
this.setState({
firstName: data.results.name.first,
lastName: data.results.name.last,
});
});
}
render() {
return this.props.children(this.state.firstName, this.state.lastName);
}
}
// used like:
<User>
{(firstName, lastName) => (
<Text>{firstName}</Text>
)}
</User>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.