我想将这两种状态作为“设置”组件中 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: []
};
}
最佳答案
我可以想到两种方法,您可以在设置
中共享您的状态。
- 使用Child as Function/Render Prop模式。
- 使用新的 React Context API .
子代作为函数/渲染属性
您可以简单地将状态传递给 this.props.children
或 this.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>
);
您可以挑选适合您口味的。
关于reactjs - 重用另一个组件的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51549396/