将数据流反应到单独的组件文件中

时间:2017-12-02 22:39:31

标签: javascript reactjs react-redux

让我说我在反应中有这个主要的js文件:

<code>
import React, { Component } from 'react';
import Data from './components/data';
import './App.css';

var todos = [
  {
    todoTitle: "My first todo",
    todoResponsible: "Kevin",
    todoDescription: "My first todo description",
    todoPriority: "low"
  },
  {
    todoTitle: "My second todo",
    todoResponsible: "Sam",
    todoDescription: "My second todo description",
    todoPriority: "medium"
  },
  {
    todoTitle: "My third todo",
    todoResponsible: "Hobbs",
    todoDescription: "My Third todo description",
    todoPriority: "high"
  }
]

class App extends Component {
  constructor(props){
    super(props);
    this.state = {
      todos
    };
  }

  `render() {
    return (
      <div className="App">
      <Data />
      </div>`
    );
  }
}

export default App;
</code>

如果我想将var todos中的数据传递到另一个文件中的此组件:

<code>
`import React, { Component } from 'react';

`class Data extends Component {
  render(){
    return(
      <ul>
        <li>
        </li>
      </ul>`
    );
  }
}

export default Data;`
</code>

我将如何这样做?我试图在线查找资源,但它只显示通过单个组件传递数据。 提前感谢您,如果可以,请提供帮助〜

2 个答案:

答案 0 :(得分:1)

您可以将todos数据作为道具传递给数据组件:

Exec=python2 $(dirname %k)/main.py

在数据组件中,class App extends Component { constructor(props){ super(props); this.state = { todos }; } `render() { return ( <div className="App"> <Data todos={this.state.todos} /> </div>` ); } } 可以轻松访问它们:

this.props.todos

答案 1 :(得分:0)

只需使用todos组件中的Data<Data todos={this.state.todos} />传递到App组件即可。然后,您可以使用以下内容从todos组件中使用Data

class Data extends Component {
  render () {
    return (
      <ul>
      {
        this.props.todos.map(todo => <li>{todo.todoTitle}</li>)
      }
      </ul>
    )
  }
}