试图将一个HTML元素作为文本传递给一个react组件。

问题描述 投票:0回答:2

我试图通过一个文本,基本上有一个新的行来分隔一个更大的句子。我试图通过将它包含在片段中作为一个反应元素来解析它。但我还是得到了 [object][Object] 而不是添加这个新行。

它基本上是一个语义-UI-反应加载器,我正在将文本传递给它。

在代码的某个地方,我正在设置状态,然后调用组件

沙盒。https:/codesandbox.iossemantic-ui-example-y8e38?file=example.js。

//Setting the state
this.setState({ text: `You will be redirected , and you may need to login.${<><br/></>} .Please read the conditions`});

 //Calling the component
 <MyComp
          message={text}

 />

 //Called Component
  import { Loader } from "semantic-ui-react";
  const MyComp: React.FunctionComponent<IProps> = props => {
    return (
       <>
        <Loader>{props.message}</Loader>
       </>   
    );
};

有人能帮帮我吗?

javascript reactjs setstate
2个回答
0
投票

你以字符串形式传递给react组件的HTML不能直接渲染,除非你使用 dangerouslySetInnerHTML

//Setting the state
this.setState({ text: `You will be redirected , and you may need to login.<br/>.Please read the conditions`});

 //Calling the component
 <MyComp
          message={text}
 />

 //Called Component
  const MyComp: React.FunctionComponent<IProps> = props => {
    return (
       <>
        <Loader><p dangerouslySetInnerHTML={{__html: props.message}}/></Loader>
       </>   
    );
};

然而,使用 dangerouslySetInnerHTML 不鼓励使用,处理这种情况的最好方法是将html作为子代传入,并有条件地启用它

//Setting the state
this.setState({ showText: true});

 //Calling the component
 <MyComp>
      {this.state.showText? <span>You will be redirected , and you may need to login. <br/> .Please read the conditions</span>: null}
 </MyComp>

 //Called Component
  import { Loader } from "semantic-ui-react";
  const MyComp: React.FunctionComponent<IProps> = props => {
    return (
       <>
        <Loader>{props.children}</Loader>
       </>   
    );
};

工作演示


1
投票

从你的代码来看,你传递了一个名为:message的道具,它包含了你想在加载器中显示的文本。

在你的代码中,这将是。

//Setting the state
this.setState(
  { 
     texts: [
        "You will be redirected, and you may need to login.", 
        "Please read the conditions"
     ] 
  });

注意:我已经把它改成了text(s),因为它现在是一个数组。

像之前一样,创建一个你的组件的实例。

<MyComp messages={texts} />

通过prop messages(重命名为messages,因为它现在是一个数组)来传递文本。

然后在你的加载器中,你可以像这样分割这几行。

<Loader>{messages.map( m => <span>{m}</span><br/>)}</Loader>

这是在添加信息,每个信息之间用一个 <br/>

我相信你可以想出一些更好的变量名称:)


0
投票

我想在下一行添加一些条件文本会更容易一些。

//Setting the state
this.setState({ 
  redirectText: "You will be redirected , and you may need to login.", 
  conditionText: "Please read the conditions"
});

 //Calling the component
 <MyComp
    redirectText={this.state.redirectText}
    conditionText={this.state.conditionText}
 />

 //Called Component
  import { Loader } from "semantic-ui-react";
  const MyComp: React.FunctionComponent<IProps> = props => {
    return (
       <>
        <Loader>
          <div>{props.redirectText}</div>
          <div>{props.conditionText}</div>
        </Loader>
       </>   
    );
};
© www.soinside.com 2019 - 2024. All rights reserved.