简体   繁体   English

reactJs中的组件

[英]Component in reactJs

I am working on react and want to specify href link to another component in react js. 我正在研究react并想在react js中指定href链接到另一个组件。 Below is the href attribute I am working on and want to redirect to another component named MenuForm. 以下是我正在使用的href属性,并且想要重定向到另一个名为MenuForm的组件。 This component has form for menu input. 该组件具有用于菜单输入的表格。 I want the form to be open after I click Menu link. 单击菜单链接后,我希望打开表单。

<a href="#" className="btn btn-primary">Menu</a>

Component I want to redirect is MenuForm <MenuForm /> 我要重定向的组件是MenuForm <MenuForm />

You need to maintain a state to show/hide your form: 您需要保持状态以显示/隐藏表单:

class MyComponent extends Component {
  state = {
    showForm: false
  }

  handleClick = event => {
    event.preventDefault()
    this.setState({showForm: true})
  }

  render() {
    return (
      <a href="#" onClick={this.handleClick} className="btn btn-primary">Menu</a>
      // ...
      {this.state.showForm && <MenuForm />}
    )
  }
}

If you use React hooks , it's even simplier: 如果您使用React钩子 ,它甚至更简单:

function MyComponent() {
  const [showForm, setShowForm] = useState(false)

  function handleClick(event) {
    event.preventDefault()
    setShowForm(true)
  }

  return (
    <a href="#" onClick={handleClick} className="btn btn-primary">Menu</a>
    // ...
    {showForm && <MenuForm />}
  )

} }

If you are using react-router-dom and want the url to change when you click the link, you can setup your router like this, 如果您使用的是react-router-dom并且希望在单击链接时更改网址,则可以这样设置路由器,

// router.js
import { BrowserRouter, Route } from "react-router-dom";
ReactDOM.render(
  <BrowserRouter>
    <Route path="/here" component={HereComponent} />
    <Route path="/there" component={ThereComponent} />
  </BrowserRouter>,
);

Then you should be able to Use the Link Component like, 然后,您应该能够使用Link组件,例如,

import { Link } from 'react-router-dom';
<Link to="/there">there</Link>

This will load the component and change the browser URL. 这将加载组件并更改浏览器URL。 You can read more about react-router-dom here: https://reacttraining.com/react-router/web/guides/quick-start 您可以在此处阅读有关react-router-dom的更多信息: https : //reacttraining.com/react-router/web/guides/quick-start

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM