[英]How can I render a new component onClick of a html button using react?
I have a component that contains a html button that when clicked on needs to call a function that renders another component and sets the state of the new component to the arguement passed in to the function that returns the new component. I have a component that contains a html button that when clicked on needs to call a function that renders another component and sets the state of the new component to the arguement passed in to the function that returns the new component. I set a state variable that is initialized with the string 'start'.我设置了一个用字符串“start”初始化的 state 变量。 When the html button is clicked the state var should change and the new component needs to be rendered.当单击 html 按钮时,state var 应该更改并且需要渲染新组件。 In my app the page doesn't load and in the minimal reproducible example I tried to make in codesandbox the state variable won't even initialize with the 'start' string在我的应用程序中,页面未加载,并且在我尝试在代码和框中制作的最小可重复示例中,state 变量甚至不会使用“开始”字符串进行初始化
import Member from "./member.js";
import { React, useState } from "react";
const Post = () => {
const [start, setStart] = useState("start");
const getProfile = (member) => {
// const addr = dispatch({ type: 'ADD_MEMBER', response: member })
console.log(member);
setStart(member)
return <Member user={member}></Member>;
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<button onClick={() => getProfile('ssssss')}>Profile</button>
</div>
);
};
export default Post;
this is the component I need to render on click这是我需要在点击时呈现的组件
import { React, useState } from "react";
const Member = (props) => {
const [user, setUser] = useState({});
return (
<div class="container">
lolololololololololololololo
{this.user}
</div>
)
}
export default Member;
There are many problems with your code.你的代码有很多问题。
A somehow working version of your code may be this:您的代码的某种工作版本可能是这样的:
import Member from "./member.js";
import { React, useState } from "react";
const Post = () => {
const [data, setData] = useState('');
const getProfile = (member) => {
// const addr = dispatch({ type: 'ADD_MEMBER', response: member })
setData(member);
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<button onClick={() => getProfile('Johny')}>Profile</button>
{data && <Member user={data}></Member>}
</div>
);
};
export default Post;
import { React, useState } from "react";
const Member = (props) => {
const [user, setUser] = useState(props.user);
return (
<div class="container">
lolololololololololololololo
{user}
</div>
);
};
export default Member;
Essentially when the button is clicked the value changes and is no longer falsy so the Member Component is rendered and gets the values as props from the data variable.本质上,当单击按钮时,值会发生变化并且不再是虚假的,因此会渲染成员组件并将值作为道具从数据变量中获取。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.