我正在通过编写玩家代号生成器来学习 React。它生成随机标签并保存一个列表,每个标签都可以进行评级。我的主要应用程序是一个使用 useState 钩子设置状态的功能组件:包含有关标签详细信息的对象数组,即星级评分系统。
我使用 react 组件 Tag 生成每个玩家代号,在其中,它使用功能组件 RenderStars 来绘制星星。每个标签都有 0 颗星,所以 5 颗空星,我希望用户通过点击多少颗星来更改评级,1-5。 RenderStars 然后将根据需要绘制任意数量的空星和填充星。
我在 App 中有一个函数 changeStars,我似乎无法成功调用任何子组件。我通过 props 将函数传递给子组件。
我尝试用箭头符号和普通函数编写 changeStars。我试过不需要任何参数。我试过只使用一个按钮在 Tag 中调用它。还有其他一些我不太记得的方法,只是弄乱了语法并尝试了 stackexchange 和文章中的其他内容。
我不绑定函数,因为它是在函数组件中创建的。
这似乎是一项超级基本的任务,我无法弄清楚。 是的,我已经阅读了 react.js 的文档
这里是一些代码,我会尽量去掉:
function App() {
const [tagInventory, setTagInventory] = useState([]);
const latestTag = tagInventory[tagInventory.length - 1] ? tagInventory[tagInventory.length -1] : null;
const handleAdd = (tag) => {
uses hook to add tag to state
}
const makeTag = () => {
creates random tag
}
function changeStars(stars,key) {
console.log(stars, key);
//this will change the star rating of an individual tag
}
return (
<main>
A bunch of amazing interface html
<section className="tagInventory">
{tagInventory.map( (item) =>
<Tag
key={item.timeStamp}
tagItem={item}
/>
) }
</section>
</main>
);
};
class Tag extends React.Component {
render() {
const item = this.props.tagItem;
const stars = this.props.tagItem.stars;
const key = this.props.tagItem.timeStamp;
const tagClass = this.props.newTag ? "tag-item new-item" : "tag-item";
return (
<div className={tagClass}>
code to generate cool tag info
</div>
<RenderStars
stars={stars}
changeStars={changeStars}
newTag={false}
key={key}
/>
</div>
);
}
}
const RenderStars = (props) => {
// ref for using symbol tag https://css-tricks.com/svg-symbol-good-choice-icons/
return (
i load svg of stars then can display as many as i need later...
now i draw 4 stars, for the example i'll stop at the first, here's the call..
{props.stars === 0 &&
<div>
<svg className="empty-star" onClick={() => props.changeStars(4,props.key)}>
<use xlinkHref="#empty-star" />
now the other stars and whatnot
}
谢谢!
答案 0 :(得分:1)
所以基本上你想将函数 changeStars
从 App 传递给 Tag,然后传递给 RenderStars,对吗?
如果是这样,您是忘记将其从 App 传递到 Tag
应用:
<section className="tagInventory">
{tagInventory.map( (item) =>
<Tag
key={item.timeStamp}
tagItem={item}
/>
) }
</section>
应该是传递函数:
<section className="tagInventory">
{tagInventory.map( (item) =>
<Tag
key={item.timeStamp}
tagItem={item}
changeStars={changeStars}
/>
) }
</section>
然后在标签上:
const changeStars = this.props.changeStars;