【问题标题】:Access Class Instance Props in React Component?在 React 组件中访问类实例道具?
【发布时间】:2021-09-15 20:01:18
【问题描述】:

我有一个只返回子类的类

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>

【问题讨论】:

  • 您确定某个组件是适合您的工具吗?您似乎没有使用组件提供的任何东西。
  • 是的,我正在使用 React Native,所以我真的没有选择,但我这样做了,所以任何需要使用该信息的东西都将放在标签 下
  • @NicholasTower 我用一个更好的例子编辑了这篇文章我的班级会是什么样子并且使用 标签你可以调用 User.firstName 等

标签: javascript node.js reactjs react-native web


【解决方案1】:

如果您希望 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>

【讨论】:

    猜你喜欢
    • 2020-05-04
    • 2021-06-25
    • 2019-02-27
    • 2017-02-14
    • 2019-11-05
    • 2020-10-18
    • 2018-09-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多