将值从一个组件传递到另一个组件

时间:2017-06-13 05:49:47

标签: reactjs

container.js -

//Here we render the recipe details and display add recipe form.   
import React, { Component } from 'react';
import './App.css';
import AddRecipe from './addrecipe.js';

class App extends Component {
  constructor(props){
  super(props);
  this.state={ recipes :[] } 
  this.addRecipe=this.addRecipe.bind(this);
  }

addRecipe (recipe) {
this.setState({ 
  recipes: [...this.state.recipes, recipe]
});
}

componentWillMount(){
this.setState({
  recipes : require('./sample-recipes')
});
} 

home(e){
 window.location='/a';
}

render() {
  return (
   <div className="App">
   <h2>Welcome to the Recipe Book</h2>
   <dl>
   {this.state.recipes.map(recipe => {
    return ( <div key={recipe.name} onClick={this.home}>
      <dt>{recipe.name}</dt>
      <dd>{recipe.ingredient}</dd>
      <div><img src='{recipe.image}' className="image"/></div>
      <hr></hr>
      </div>
      )
  })
 }
 </dl>
 <button className="addButton" onClick={() => 
  {this.setState({ display: !this.state.display })}}>
  Add Recipe
  </button>
  <AddRecipe addRecipe={this.addRecipe} 
  display={this.state.display} />
  </div>
  );
 }
}

export default App;

在home函数中,它将页面指向('/ recipe')文件store.js

import React, { Component } from 'react';
import AddRecipe from './addrecipe.js';

var StorePicker = React.createClass({
  render : function() {
  return (
   <form className="store-selector">
    <h2>{recipe.name}</h2> --->//gives error recipe is not defined.
    </form>
   )
 }
 });

export default StorePicker;

如何在('/ recipe')给出的新页面中显示recipe.name,ingredients,image。还有另一个文件addrecipe.js,它创建一个表单来从用户那里获取输入。

这是我的index.js文件 -

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import AddRecipe from './addrecipe';
import StorePicker from './store'; 
import App from './container'

var ReactRouter = require('react-router');
var Router  = ReactRouter.Router;
var Route = ReactRouter.Route;
var Navigation = ReactRouter.Navigation;
import createHistory from 'history/createBrowserHistory'

var routes = (
  <Router history={createHistory()}>
    <switch>
        <Route exact={true} path="/recipe" component={StorePicker} />
        <Route exact={true} path="/" component={App}/>
    </switch>
 </Router>
    );

  ReactDOM.render(routes, document.getElementById('root'));

0 个答案:

没有答案