如何将数据从父母传递给孩子。为什么这不起作用? 无法在子组件中显示数据
class App extends React.Component {
constructor(props){
super(props);
const customers = [ 'Guacamole', 'Beef', 'Bean' ];
}
render() {
return (
<div>
1) DataGrid
<Api customers = {this.customers} />
</div>
);
}
}
export default App;
class Api extends React.Component {
render() {
return (
<div>
{this.props.customers}
</div>
)}
}
答案 0 :(得分:0)
尝试使用React state
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
customers =['Guacamole', 'Beef', 'Bean'];
}
}
render() {
return (
<div>
1) DataGrid
<Api customers={this.state.customers} />
</div>
);
}
}
export default App;
class Api extends React.Component {
render() {
return (
<div>
{this.props.customers}
</div>
)
}
}
或者您可以只使用不带state
的变量
class App extends React.Component {
customers = ['Guacamole', 'Beef', 'Bean'];
constructor(props) {
super(props);
}
render() {
return (
<div>
1) DataGrid
<Api customers={this.customers} />
</div>
);
}
}
export default App;
class Api extends React.Component {
render() {
return (
<div>
{this.props.customers}
</div>
)
}
}
答案 1 :(得分:0)
只是改变
const customers = [ 'Guacamole', 'Beef', 'Bean' ];
到
this.customers = [ 'Guacamole', 'Beef', 'Bean' ];
答案 2 :(得分:0)
您将customers
内的const
变量定义为constructor
。
该变量将在执行此方法时生效,然后消失。
您必须执行类似this.customers
的操作,这样,变量将是组件实例的属性,可以在其他方法中使用。您可以使用@kkangil建议的this.state
,也可以同时使用this.customers
。区别在于,React跟踪state
之外的其他信息,以进行tigger重新渲染。
class App extends React.Component {
constructor(props){
super(props);
this.customers = [ 'Guacamole', 'Beef', 'Bean' ];
}
// ...
}
答案 3 :(得分:0)
为什么这不起作用?因为this.customers === null
如何将数据从父母传递给孩子?
正确使用constant
class App extends React.Component {
constructor(props){
super(props);
}
render() {
const customers = [ 'Guacamole', 'Beef', 'Bean' ];
return (
<div>
1) DataGrid
<Api customers = {customers} />
</div>
);
}
}
export default App;
class Api extends React.Component {
render() {
return (
<div>
{this.props.customers}
</div>
)}
}
或正确使用state
:
class App extends React.Component {
constructor(props){
super(props);
this.state = {
customers: [ 'Guacamole', 'Beef', 'Bean' ],
};
}
render() {
return (
<div>
1) DataGrid
<Api customers = {this.state.customers} />
<div onClick={() => {this.setState({customers: ['Beef', 'Apple']})}}>Change state</div>
</div>
);
}
}
export default App;
class Api extends React.Component {
render() {
return (
<div>
{this.props.customers}
</div>
)}
}
或正确使用this
:
class App extends React.Component {
constructor(props){
super(props);
this.customers = [ 'Guacamole', 'Beef', 'Bean' ];
}
render() {
return (
<div>
1) DataGrid
<Api customers = {this.customers} />
</div>
);
}
}
export default App;
class Api extends React.Component {
render() {
return (
<div>
{this.props.customers}
</div>
)}
}