【问题标题】:How to call a component class function in my App.tsx?如何在我的 App.tsx 中调用组件类函数?
【发布时间】:2022-11-11 21:06:20
【问题描述】:

我是 React Native 的新手,我正在尝试使用 Expo 开发一个移动应用程序。

我试图在我的 App.tsx 中调用组件类的函数。我不希望该函数是静态的,因为我需要访问我的状态变量,该变量位于我的类的构造函数中。

应用程序.tsx

const App = () => {

  const [variable, setVariable] = useState('');

  useEffect(() => {
      //doing some stuff 
  }, [])
  
  Class1.method(variable);
  
  [...]
}

Class1.tsx

class Class1 extends Component<any, any> {
  
  constructor(props: any){
    super(props);

    this.state = {
      company_name: [],
    }
  }

  method(param: any) {
    Object.values(param).map(function(d: any, idx){
      this.state.company_name = [...this.state.company_name, d];
    });
  }

  [...]

所以问题是我的 App.tsx 中有一个数组,我想将它传递给我的 Class1。

有可能这样做还是我错过了什么?

提前致谢

【问题讨论】:

    标签: reactjs typescript expo native


    【解决方案1】:

    您应该通过在您的Class1.tsx 底部添加export default Class1;,在类声明之后导出您的Class1 组件。

    然后您将能够导入该组件并在App.tsx 文件中使用它。

    Code splitting 上阅读此 React 文档以了解更多信息。

    【讨论】:

      【解决方案2】:

      把你的数组放在道具中

      const App = () => {
        const [names, setNames] = useState([]);
      
        const addCompanyName = (name) => {
          setNames([...names, name]);
        }
      
        const addRandomCompany = () => {
          addCompanyName(Math.random().toString());
        }
      
        return <>
          <Button title='random name' onPress={addRandomCompany}/>
          <Child companyNames={names}/>
        </>
      }
      
      const Child = ({ companyNames }) => {
        return <>
          {companyNames.map((name) => <Text>{name}</Text>)}
        </>
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-12-28
        • 2021-03-22
        • 1970-01-01
        • 2021-05-13
        • 1970-01-01
        • 2020-12-12
        • 2021-05-23
        • 2019-12-11
        相关资源
        最近更新 更多