简体   繁体   English

是否可以动态处理作为道具传递给组件的值?

[英]Is it possible to manipulate a value that is passed to a component as Props dynamically?

I am new to React and I am trying to understand the following basic: 我是React的新手,我想了解以下基本知识:

Is it possible to manipulate a value that is passed to a component as props dynamically? 是否可以动态处理作为prop传递给组件的值? Eg trough the console on the client? 例如通过客户端上的控制台? Will that lead to a rerender of the component? 这会导致组件的重新渲染吗?

I know that it is possible to pass a value to a child component from its parent, and as soon as the parent rerenders, the child component is rerendered as well with the new value. 我知道可以将值从其父级传递给子级组件,并且一旦父级重新渲染,子级组件也将使用新值重新呈现。

But can you achieve the same behaviour by somehow manipulate the passed value directly? 但是您可以通过某种方式直接操纵传递的值来实现相同的行为吗? eg 例如

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

ReactDOM.render(
  <Welcome name="Sara" />,
  document.getElementById('root')
);

Output is: Hello, Sara 输出是:你好,萨拉

I want to achieve something like this, without using a parent element: 我想不使用父元素就实现这样的事情:

 function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}
var name = "test"; 
ReactDOM.render(
  <Welcome name={name} />,
  document.getElementById('root')
);

Output is: "test" 输出为:“测试”

Now if I set name in console to name = "X" it changes nothing, name seems to be a completely different variable. 现在,如果我在控制台中将name设置为name = "X"它什么也不会改变,所以name似乎是一个完全不同的变量。

To answer your question: inputing variable changes in the console (let's assume you are using chrome dev tools) will NOT affect the reactjs code you have written. 回答您的问题:在控制台中输入变量更改(假设您使用的是chrome dev工具)不会影响您编写的reactjs代码。

If you are changing the variable at the console level once the page has loaded, then the original variable "name" will have already rendered with the assigned value of "test". 如果在页面加载后在控制台级别更改变量,则原始变量“名称”将已经使用分配的值“ test”进行渲染。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM