Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

javascript - 调用组件时如何设置状态?(How can I set state when calling component?)

I'm very new to react, and got a bit stuck already.(我刚开始反应,已经有点卡住了。)

I've made a component for an Article Topper that's repeated many times across the site.(我已经为“文章排行榜”制作了一个组件,该组件在整个网站上已重复多次。) It has a logo, a title, and a few share buttons and just sits above the article with the name of the article.(它具有徽标,标题和几个共享按钮,并位于文章上方,并带有文章名称。) What I want to do is update the title name when I call the component, as each article will have a different name.(我要做的是在调用组件时更新标题名称,因为每篇文章都有不同的名称。) constructor(props) { super(props); this.state = { topper: [] }; } render() { return ( <div className="articletopper"> <div className="left-cell"> <p> <img className="logo" alt="" src={require("../images/logo.png")} /> {this.state.topper} </p> </div> ... Then in the actual page I want to call this and update the topper state.(然后在实际页面中,我想调用它并更新topper状态。) render() { return ( <div className="Team"> <Articletopper>Title of Article?</Articletopper> </div> ); } } I am aware you are not supposed to update state when you call a component, just wondered if there was a way.(我知道您在调用组件时不应该更新状态,只是想知道是否有办法。) The purpose of this is just to make the code cleaner when creating a new article.(这样做的目的只是为了在创建新文章时使代码更整洁。) Thanks in advance for any help.(在此先感谢您的帮助。) EDIT: Thanks for the responses, sorry if I wasn't clear.(编辑:感谢您的答复,对不起,如果我不清楚。) I want to update the title of the article without pasting tons of html each time.(我想更新文章的标题,而不必每次都粘贴大量的html。) I think I need to use props based on what other people have said.(我想我需要根据其他人所说的来使用道具。) For example I want to do:(例如,我想做:) <ArticleTopper> Article 1 Title </ArticleTopper> <p> Article1... </p> <ArticleTopper> Article 2 Title </ArticleTopper> <p> Article2... </p> and so on...(等等...)   ask by Ragonkai translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can initialize the state by props while constructing.(您可以在构造时通过道具初始化状??态。)

If the title you give the component can vary over time,you may need to ask lifecycle method componentDidUpdate for help.(如果您给组件指定的title会随时间变化,则可能需要向生命周期方法componentDidUpdate寻求帮助。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...