【发布时间】:2017-05-19 10:22:46
【问题描述】:
我有一个 TopNab 栏(组件),其中包含一个 SearchBar 组件。我的主要组件正在渲染 TopNav、主要容器组件(配置文件)和页脚组件。我希望我的 SearchBar 组件将其状态传递给主容器组件,以便 Profile 组件可以使用它。
我正在尝试构建的内容: 用户在搜索栏中输入名称并提交。 与用户名匹配的配置文件显示在主容器组件中。
现在我有一个可以呈现用户配置文件的组件。我还有一个组件,它可以对用户提交的值进行状态更新。我需要做的是将此用户提交的值传递给我的配置文件组件,以便呈现正确的配置文件。
这是可能的还是我需要重新构建我的组件以便将搜索包含在 Profile 组件中?
搜索栏
import React, { Component, PropTypes } from 'react';
import Profile from './Profile';
class SearchBar extends Component {
constructor(props){
super(props)
this.state = {
name: ''
}
}
handleChange(e) {
this.setState({
name: e.target.value
});
}
handleSubmit(e) {
e.preventDefault();
console.log("searching for NAME " + this.state.name);
let profileName = this.state.name;
//PASS STATE TO PROFILE COMPONENT
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit.bind(this)}>
ARMORY BETA
<input type="text" placeholder="Enter Name"
name="name"
value={this.state.name}
onChange={this.handleChange.bind(this)} />
<button className="btn btn-success" type="submit">Search</button>
</form>
</div>
)
}
}
export default SearchBar;
简介
import React, { Component, PropTypes } from 'react';
import SearchBar from './SearchBar';
import ProfileContainer from '../containers/ProfileContainer';
class Profile extends Component {
render() {
return (
<div className="cols2">
<div>[IMG]</div>
<div>
<ProfileContainer name={this.props.name}/>
</div>
</div>
)
}
}
Profile.PropTypes = {
name: PropTypes.string
}
Profile.defaultProps = {
name: ''
}
export default Profile;
主要
import React, { Component } from 'react';
import TopNav from './TopNav';
import Footer from './Footer';
import Profile from './Profile';
class Main extends Component {
render() {
return (
<div className="container-fluid">
<div className="row">
//TopNav calls SearchBar
<TopNav />
</div>
<div className="row">
<Profile />
</div>
<div className="row">
<Footer />
</div>
</div>
)
}
}
export default Main;
【问题讨论】:
标签: reactjs search components state