为什么Link不能在react.js中工作?

时间:2016-12-25 08:37:20

标签: javascript reactjs react-router

我正在使用react-routerLink to功能。我想在点击按钮时显示second component,但我的代码无效

http://codepen.io/anon/pen/GNadKZ?editors=1010

var Router = ReactRouter;

var DefaultRoute = Router.DefaultRoute;
var Link = Router.Link;
var Route = Router.Route;
var RouteHandler = Router.RouteHandler;

class Abc extends React.Component {
  handle(){
    alert('move to second component')
  }
   render (){
     return (<div><h1>second</h1><Link to="about"><button onClick={this.handle}>move to second page</button></Link></div>);

   }
}
class Pqr extends React.Component {
   render (){
     return (<div><h1>second</h1><button>click</button></div>)

   }
}

ReactDOM.render((<Router>
    <Route path="/" component={Abc}>
      <Route path="about" component={Pqr}/>
      </Route>
      <Route path="*" component={NoMatch}/>
    </Route>
  </Router>),document.getElementById('root'));

第一个组件中有一个按钮。我想在点击按钮时显示第二个组件。

1 个答案:

答案 0 :(得分:0)

在第一个组件的渲染中声明{this.props.children}

 return (<div><h1>second</h1><Link to="about"><button onClick={this.handle}>move to second page</button></Link> {this.props.children} </div>);

检查它是否正常工作:

var Router = ReactRouter;

var DefaultRoute = Router.DefaultRoute;
var Link = Router.Link;
var Route = Router.Route;
var RouteHandler = Router.RouteHandler;

class Abc extends React.Component {
  handle(){
    alert('move to second component')
  }
   render (){
     console.log('inside first render');
     return (<div><h1>second</h1><Link to="about"><button onClick={this.handle}>move to second page</button></Link>{this.props.children}</div>);

   }
}
class Pqr extends React.Component {
   render (){
     return (<div><h1>second</h1><button>click</button></div>)

   }
}

ReactDOM.render((<Router>
    <Route path="/" component={Abc}>
      <Route path="about" component={Pqr}/>  
      <Route path="*" component={NoMatch}/>
     </Route>   
  </Router>),document.getElementById('root'));