我正在读 Apollo documentation然后我看到了下面的代码。 看起来来自 Query 组件本身的加载、错误和数据可以传递给 props.children 接受函数。我如何实现这样一个简单的组件,它可以获取自己的值并将其传递给其子组件?
import gql from "graphql-tag";
import { Query } from "react-apollo";
const GET_DOGS = gql`
{
dogs {
id
breed
}
}
`;
const Dogs = ({ onDogSelected }) => (
<Query query={GET_DOGS}>
{({ loading, error, data }) => {
if (loading) return "Loading...";
if (error) return `Error! ${error.message}`;
return (
<select name="dog" onChange={onDogSelected}>
{data.dogs.map(dog => (
<option key={dog.id} value={dog.breed}>
{dog.breed}
</option>
))}
</select>
);
}}
</Query>
);
我尝试过什么:
1) 使用发送数据的函数覆盖 props.children
。 (我猜 apollo 查询组件使用了这种方法,因为根据它的 source code 。
2)克隆 child 然后发送数据,这对我来说不成功。
最佳答案
允许子级成为函数是 React 中的常见模式。连新Context API使用这种模式。
如果你看source code of the react-apollo Query component您可以看到它只是将 this.props.children
作为函数调用。
render() {
const { children } = this.props;
const queryResult = this.getQueryResult();
return children(queryResult);
}
有关 Function as Children 模式的更深入说明,请查看 React documentation关于渲染 Prop 。
关于javascript - Apollo Query 组件如何使用它的自身值作为回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51745102/