我是React的新手,尝试将值从父组件传递到子组件再传递到props并将值存储在状态中。但是它甚至没有调用console.log语句
这是我通过单击按钮更改字符串的功能
let actionToPerform = "";
function changeEdit(){
if(actionToPerform === 'edit'){
actionToPerform = 'new'
}else{
actionToPerform = 'edit'
}
}
在父组件的渲染中,我有这个:
<Edit action={actionToPerform}
/>
子组件
从'react'导入React; 从'./edit.module.css'中导入*作为样式;
export default class Edit extends React.Component {
constructor(props){
super(props);
this.state = {actionToPerform: this.props.actionToPerform}
console.log("props:" + props)
console.log("parsed state: " + this.state)
}
showContent = ()=>{
if(this.state.actionToPerform == "edit"){
return <div>Shoppinliste bearbeiten</div>
}
}
render() {
return (
this.showContent
)
}
}
我的目标是基于通过单击按钮更改的状态来显示div或不显示div。
答案 0 :(得分:1)
您正在将 action 道具传递给孩子,但会解析 actionToPerform 。您需要在子级中解析 action 。
控制台日志应位于构造函数之外。
export default class Edit extends React.Component {
constructor(props){
super(props);
this.state = {actionToPerform: this.props.action}
}
showContent = ()=>{
console.log("props:" + props)
console.log("parsed state: " + this.state)
if(this.state.actionToPerform == "edit"){
return <div>Shoppinliste bearbeiten</div>
}
}
render() {
return (
this.showContent
)
}
}