我正在尝试理解text <- "Conv. Rev. ID Order path_no
0 0 1 1 1
1 50 1 2 1
0 0 1 3 2
1 100 1 4 2
0 0 2 1 1
0 0 2 2 1
1 150 2 3 1
1 100 2 4 2"
df <- read.table(text = text, stringsAsFactors = FALSE, header = TRUE)
以帮助我将孩子的值传递给父母。我有一个state.props
(子),当单击一个链接时,它应该将值传递给header component
(父)内的方法。然后,此方法设置用于其他事物的值的状态。我已经尝试在App.js文件中绑定该方法,但这不起作用。点击链接后出现错误:App component
Header.js
×
TypeError: _this.changeSearchState is not a function
App.js
import React, { Component } from "react";
import { Link } from 'react-router-dom';
class Header extends Component {
changeSearch = (e) => {
e.preventDefault();
var type = this.value;
this.changeSearchState(type);
}
render() {
return (
<header>
<div className="float-right top-bar">
<Link onClick={this.changeSearch} value="users" to="/users">Users</Link>
<Link onClick={this.changeSearch} value="feedback" to="/feedback">Feedback</Link>
...
</div>
</header>
)
}
}
export default Header;
答案 0 :(得分:1)
您应该只在一个位置更新状态。因此,您应该在Parent
组件中对其进行更新,然后将其传递给Child
。您可以像普通道具一样访问从父级传递给子级的方法。像这样:
<强> App.js 强>
class App extends Component {
constructor(props) {
super(props)
this.state = {
isOpen: false,
dataType: ''
}
this.changeSearchState = this.changeSearchState.bind(this);
}
changeSearchState = (dataType) => {
this.setState({
dataType: dataType
});
}
render() {
return (
<Header changeSearchState={this.changeSearchState} /> //this is what you want!!!
)
}
<强> Header.js 强>
import React, { Component } from "react";
import { Link } from 'react-router-dom';
class Header extends Component {
changeSearch = (e) => {
e.preventDefault();
var type = this.value;
this.props.changeSearchState(type); // call it here with this.props!!
}
render() {
return (
<header>
<div className="float-right top-bar">
<Link onClick={this.changeSearch} value="users" to="/users">Users</Link>
<Link onClick={this.changeSearch} value="feedback" to="/feedback">Feedback</Link>
...
</div>
</header>
)
}
}
export default Header;
答案 1 :(得分:1)
我认为您希望将changeSearchState
作为道具传递给Header
组件。
在render()
App.js :
<Header
changeSearchState={this.changeSearchState}
/>
然后从 Header.js :
访问它changeSearch = (e) => {
e.preventDefault();
var type = this.value;
this.props.changeSearchState(type)
}
您可以阅读有关组件和道具的更多信息here。