反应this.props.title为空!为什么?

时间:2018-08-25 10:33:14

标签: javascript reactjs react-router jsx

我有3个状态(状态,标题,舞蹈)

我使用react-router,react-switch,React.cloneElement。

  

App.jsx

   var React = require('react');
    var io = require('socket.io-client');
    var Router = require('react-router');
    var RouteHandler = require('react-router').RouteHandlerl;
    var Header = require('./parts/Header');
    module.exports =  class App extends React.Component {
      constructor(){
        super();

        this.state = {
          status: 'disconnected',
          title:'no Tile',
          dance: 'dance'
      };
      }

        render() {
              return (
                <div>
                  <Header title={this.state.title} status={this.state.status }  />
                  {React.cloneElement(this.props.children,this.state)} 
                  </div>
              );
            }
          }

并想在观众中花费状态(标题)!

问题是 this.props.title为空,为什么? 必须this.props.title =='no Tile'

  

Audience.jsx

var React = require('react');

    module.exports =  class Audience extends React.Component {

        render(){// this.props.title is null ???
            return (<h1>Audience : {this.props.title}</h1>);
        }
    }

在应用客户端中运行

  

app-client.jsx

  var React = require('react');
    var Router = require('react-router-dom');
    var BrowserRouter = require('react-router-dom').BrowserRouter;
    var Route = require('react-router-dom').Route;
    var Switch = require('react-router-dom').Switch;
    var ReactDOM = require("react-dom");
    var App = require("./components/APP");
    var Audience = require("./components/Audience");


     class Run extends React.Component {

        render(){
            return( 
            <BrowserRouter  >
                <Switch title={this.props.title} > 
                    <Route  path="/" component={Audience}   title={this.props.title} />

               </Switch>
           </BrowserRouter>
           );
        }
    }


        ReactDOM.render( 
       <App >
            <Run  />
        </App>
       ,
        document.getElementById('react-container')
);

1 个答案:

答案 0 :(得分:1)

因为“路线”组件未将道具向下传递到匹配的组件。尝试这样的事情:

<Route  path="/" render={() => <Audience title={this.props.title} />} />

Check out more examples from react-router docs.