Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/444.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在react中将数据从一个组件传输到另一个组件?_Javascript_Reactjs_Typescript - Fatal编程技术网

Javascript 如何在react中将数据从一个组件传输到另一个组件?

Javascript 如何在react中将数据从一个组件传输到另一个组件?,javascript,reactjs,typescript,Javascript,Reactjs,Typescript,有一个显示帖子的代码,单击帖子可以显示该帖子的全部内容 import React from "react"; type respX = { "id": any, "userId": any, "title": any, "body": any, } interface PropsI { } interface StateI { data: respX[]; changedBody: string changedTitle: stri

有一个显示帖子的代码,单击帖子可以显示该帖子的全部内容

import React from "react";


type respX = {
    "id": any,
    "userId": any,
    "title": any,
    "body": any,
}

interface PropsI {
}

interface StateI {
    data: respX[];
    changedBody: string
    changedTitle: string
}

export class ComponentPostList extends React.Component<PropsI, StateI> {

    state: StateI = {data: [], changedBody: '', changedTitle: 'Click to choose article'}

    async getPostById(id: any) {
        const myResponse = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`);
        const myJson = await myResponse.json();
        this.setState({changedBody: myJson.body, changedTitle: myJson.title});
    }

    async componentDidMount() {
        const response = await fetch(`https://jsonplaceholder.typicode.com/posts/`);
        const json = await response.json();
        this.setState({data: json});
    }


    render() {
        return (
            <div className="About">
                <div className="content">
                    <div className="title">{this.state.changedTitle}</div>
                    <div className="article">{this.state.changedBody}</div>
                </div>
                {this.state.data.map(el => (
                    <li onClick={e => this.getPostById(el.id)} key={el.id}>
                        {el.title}
                    </li>
                ))}
            </div>
        );
    }
}
从“React”导入React;
类型respX={
“id”:任何,
“用户ID”:任何,
“标题”:任何,
“身体”:任何,
}
界面属性{
}
接口状态{
数据:respX[];
changedBody:string
changedTitle:string
}
导出类ComponentPostList扩展React.Component{
状态:StateI={data:[],changedBody:'',changedTitle:'单击以选择文章'}
异步getPostById(id:any){
const myResponse=等待获取(`https://jsonplaceholder.typicode.com/posts/${id}`);
const myJson=wait myResponse.json();
this.setState({changedBody:myJson.body,changedTitle:myJson.title});
}
异步组件didmount(){
const response=等待获取(`https://jsonplaceholder.typicode.com/posts/`);
const json=await response.json();
this.setState({data:json});
}
render(){
返回(
{this.state.changedTitle}
{this.state.changedBody}
{this.state.data.map(el=>(
  • this.getPostById(el.id)}key={el.id}> {el.title}
  • ))} ); } }
    如何将数据从一个组件传输到另一个组件?在一个组件中呈现文章标题,在另一个组件中呈现文章的完整内容。这些组件位于同一级别:

      <ComponentPostList data = {data} onClick = (getPostById) />
      <ComponentArticle post = {post} />
    

    在这种情况下,我更喜欢使用回调函数。这是解决你问题的简单方法

    您有两个组件。您可以将函数传递给子组件,以从子组件接收返回父组件的值

    class Parent extends React.Component {
      state = { post: null, data: null }
    
      async componentDidMount() {
        const data = await fetchData()
        this.setState({ data })
      }
    
      getPostById = async (id: any) => {
        const myResponse = await fetch(url);
        const post = await myResponse.json();
        this.setState({ post });
      }
    
      render() {
        <ComponentPostList 
          data={this.state.data} 
          postTitle={this.state.post.title} 
          changedBody={this.state.post.changedBody} 
          handleClick={this.getPostById}
        />
        <ComponentArticle postBody={this.state.post ? this.state.post.body : ''} />
      }
    }
    
    

    ComponentArticle
    上,您使用道具访问值来呈现内容。

    您尝试过上下文API吗?@Reza Ghorban不,我没有。。有必要在这里使用它吗?没有,但它是一个选项。“提升状态”-通过bothin
    getPostById
    函数父级中的状态,您可以将post数据发送到
    ComponentPostList
    ComponentArticle
    的父级,并将其存储到state,然后作为props传递到
    ComponentArticle
    我在这行this.setState({post})中得到了一个错误;错误:未处理的拒绝(TypeError):this.setState不是函数,因为我的方法没有绑定到类。我改变了答案,改为使用箭头函数。箭头函数可以自动绑定到类。因此它可以调用类的任何方法和属性。
    class ComponentPostList extends React.Component {
        render() {
            return (
                <div className="About">
                    <div className="content">
                        <div className="title">{this.props.postTitle}</div>
                        <div className="article">{this.props.changedBody}</div>
                    </div>
                    {this.props.data.map(el => (
                        <li onClick={e => this.props.handleClick(el.id)} key={el.id}>
                            {el.title}
                        </li>
                    ))}
                </div>
            );
        }
    }