reactjs - 重用另一个组件的方法

标签 reactjs

我想将这两种状态作为“设置”组件中 getSettings 方法的结果传递给“添加”组件。有什么办法可以做到这一点而不将该方法复制到其他组件吗?

谢谢

设置组件

export class Settings extends Component {
    constructor(props) {
        super(props);

        this.state = {
         languages: [],
         currencies: []
        };
    }

    getSettings() {
        fetch('/settings', {
            method: 'get',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            }
        })
        .then( ... )
        .then(json => {
            this.setState({
                currencies: json.currencies,
                languages: json.languages
            });
        })
    }
}

添加组件

export class Add extends Component {
    displayName = Add.name

constructor(props) {
    super(props);

    this.state = {
    languages: [],
    currencies: []
    };
}

最佳答案

我可以想到两种方法,您可以在设置中共享您的状态。

  1. 使用Child as Function/Render Prop模式。
  2. 使用新的 React Context API .

子代作为函数/渲染属性

您可以简单地将状态传递给 this.props.childrenthis.props.render

class Settings extends Component {
  state = {
    languages: [],
    currencies: []
  };
  getSettings = () => {
    // fetch('/settings', {
    //     method: 'get',
    //     headers: {
    //         'Accept': 'application/json',
    //         'Content-Type': 'application/json'
    //     }
    // })
    // .then( ... )
    // .then(json => {
    //     this.setState({
    //         currencies: json.currencies,
    //         languages: json.languages
    //     });
    // })
    this.setState({
      currencies: ["Dollar", "Euro", "Won"],
      languages: ["English", "French", "Korean"]
    });
  };

  componentDidMount() {
    this.getSettings();
  }

  render() {
    return <div>{this.props.children(this.state)}</div>;
  }
}

像这样使用它。

const renderComponents = (currencies, languages) => {
  const currencyItems = currencies.map(currency => (
    <li key={currency}>{currency}</li>
  ));
  const languageItems = languages.map(language => (
    <li key={language}>{language}</li>
  ));
  return (
    <div>
      <h3>currencies</h3>
      <ul>{currencyItems}</ul>
      <hr />
      <h3>languages</h3>
      <ul>{languageItems}</ul>
    </div>
  );
};

const AppChildAsFunction = () => (
  <div>
    <h2>Using Child as Function</h2>
    <Settings>
      {({ currencies, languages }) => renderComponents(currencies, languages)}
    </Settings>
  </div>
);

使用新的 React Context API

创建并导出新的设置提供者和使用者

SettingsContext.js

import React, { Component } from "react";

const defaultValue = {
  currencies: ["Dollar", "Euro", "Won"],
  languages: ["English", "French", "Korean"]
};
const { Provider, Consumer: SettingsConsumer } = React.createContext(
  defaultValue
);

class SettingsProvider extends Component {
  state = {
    languages: [],
    currencies: []
  };
  render() {
    return <Provider value={this.state}>{this.props.children}</Provider>;
  }
}

export { SettingsProvider, SettingsConsumer };

而且用法也差不多

App.js

import { SettingsProvider, SettingsConsumer } from "./SettingsContext";
...
const AppWithContext = () => (
  <div>
    <h2>Using Context API</h2>
    <SettingsConsumer>
      {({ currencies, languages }) => renderComponents(currencies, languages)}
    </SettingsConsumer>
  </div>
);

您可以挑选适合您口味的。

CodeSandBox 上的工作演示
Edit so.answer.51549396

enter image description here

关于reactjs - 重用另一个组件的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51549396/

相关文章:

error-handling - 我如何处理异常?

javascript - 使用 Netlify lambda 函数从 GatsbyJS 站点发送电子邮件

javascript - componentWillMount 中的异步调用在 render 方法后完成

javascript - 如何在 react.js 表单中创建多个提交按钮?

android - 我的 Android 版 React Native 应用程序需要太多权限

reactjs - 在 react 导航 v5 上使用带有 useRoute 的 typescript

reactjs - 带有React和Babel语法错误的Brunch.io

javascript - 使用 gatsby-source-google-spreadsheet 将表格中的链接插入 Gatsby

javascript - 从本地主机reactjs应用程序打开外部链接

javascript - 如何修复控制台警告 "The resource ... was preloaded using link preload but not used within a few seconds from the window' s 加载事件”?