是否有可能在ReactJS中实现独立组件之间的通信?

问题描述 投票:1回答:2

我有两个组成部分。这些组件位于不同的路径上。 'CreateItem'组件使我有可能创建新项目。我将新项目存储到数组中。数组将包含新创建的项目。我想将这个修改过的数组发送到组件'Main',我将迭代这些项并将它们显示为列表。

这是我的代码:

1)index.js文件:

import React, { Component } from 'react';
import { render } from 'react-dom';
import { BrowserRouter, Route } from 'react-router-dom'
import {Main} from "./components/Main"
import {CreateItem} from "./components/CreateItem"
import {CurrentItem} from "./components/CurrentItem"


render(
    <BrowserRouter>
        <div> 
            <Route exact path="/" component={Main}/> 
            <Route path="/create_item" component={CreateItem}/>
            <Route path="/item" component={CurrentItem}/>
        </div>
    </BrowserRouter>,
    document.getElementById('app')
);

2)Main.js

import React from 'react';
import { withRouter } from 'react-router-dom';
import { Route, browserHistory } from 'react-router-dom';

export class Main extends React.Component {

    render(){
        const ToCreateItemPageButton = () => (
            <Route render={({ history}) => (
                <button type='button' onClick={() => { history.push('/create_item') }}>Move to create item page!</button>
             )}
            />
        )

        return (
            <div>
                <h1>Main Page</h1>
                <ToCreateItemPageButton/>
            </div>
        );
    }
}

3)CreateItem.js

import React from 'react'; 
import { Route, browserHistory } from 'react-router-dom';

export class CreateItem extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            mainArray: [],
            item: {},
            item_id: 0,
        };
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleChange(event) {
        this.setState({item: {item_id: this.state.item_id, 
                       name:event.target.value}});
    }

    handleSubmit(event) {
        if (this.state.item.name.length > 0) {
        this.state.mainArray.push(this.state.item);
        this.state.item_id = this.state.item_id + 1;
        let data = JSON.stringify(this.state.mainArray);
        localStorage.setItem('mainObject', data);
        this.setState(
            {mainArray : this.state.mainArray,
            item_id : this.state.item_id,}
        );
        event.preventDefault();
        }
    }

    render(){
        const ToMainPageButton = () => (
            <Route render={({ history}) => (
                <button type='button' onClick={() => { history.push('/') }}>Move to main page!</button>
             )}
            />
        )
        return (
            <div>
                <h1>Create new item</h1>
                <ToMainPageButton/>
                <form onSubmit={this.handleSubmit}>
                    <label>
                          <input type="text" value={this.state.value} onChange={this.handleChange} />
                    </label>
                <input type="submit" value="Submit" />
                </form>
            </div>

        );
    }
}

所以我想要的是有可能将我的mainArray从'CreateItem'组件转移到'Main'组件。

reactjs
2个回答
1
投票

你可以像这样重定向和发送数据:

this.props.history.push({
  pathname: '/target-path',
  data: [/*your data*/]
});

并在目标组件上接收它,以便:

const { data } = this.props.location;

1
投票

简短回答 - 是的,可以像fiddle一样使用容器组件。

因此,我们的想法是让您将项目数组保持在容器状态,并将其传递给“迭代”组件以及用于处理传入项目的回调。

// container component
class Container extends React.Component {
  constructor(props){
    super(props);
    this.state = {
        array: ['Hello', 'Stack', 'Overflow']
    }
    this.handleOnAdd = this.handleOnAdd.bind(this)
  }

  handleOnAdd(item){
    this.setState({
        array: [...this.state.array, item]
    })
  }

  render() {
    return (
      <div>
        // pass shared props to "display" component
        <ChildOneDisplay items={this.state.array} />  
        // pass a callback to CreateItem component
        <ChildTwoAdd onAdd={this.handleOnAdd} />  
      </div>
    );
  }
}

// display component

class ChildTwoAdd extends React.Component{
  constructor(props){
    ...
    this.handleAdd = this.handleAdd.bind(this)
  }
  handleAdd(){
    this.props.onAdd(this.state.item);
    ...
  }
  render(){
    return(
      <div>
        <input
          name="item"
          type="text"
          onChange={this.handleChange}
          value={this.state.item}
        />
        <button onClick={this.handleAdd}>Add Me</button>
      </div>
    )
  }
}

所以你需要的是用一个容器组件包装你的两个路由,并像我在这个例子中那样将props传递给它们。

// So your container should look like the following one

render(){
  return (
    <div>
       <Route exact path="/" render={() => <Main items={this.state.array}}/> 
       <Route path="/create_item" render={() => <CreateItem onAdd={this.handleAdd}/>}/>
    </div>
  )
}

// And render it as the following
<BrowserRouter>
  <Container />
  <Route path="/item" component={CurrentItem}/>
</BrowserRouter>

此外,我建议查看redux - 这是用于管理您的应用程序状态的库。

谢谢!

© www.soinside.com 2019 - 2024. All rights reserved.