我如何将字符串转换为纯HTML?

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

不确定正确的词汇,因此我在搜索时遇到了麻烦。基本上我发送一个获取请求

http://localhost:8080/api/v1/getstuff

它将向我返回用于向下滚动的选项标签。基本上使用axios,

  componentDidMount() {

    axios.get("http://localhost:/8080/api/v1/getstuff"
    )
      .then((response) => {
        this.setState({ stuff: response.data })

      })
      .catch(function (error) {
        console.log(error);

      });

  }

东西现在设置为此:

并且我将其放置在一个选择标签中,但它显示为

"<option value='hello'>hello</option>
<option value='hello2'>hello2</option>
<option value='sss'>sss</option>"

而不是

<option value='hello'>hello</option>
<option value='hello2'>hello2</option>
<option value='sss'>sss</option>

哪个做到了,所以选项标签不会显示。如何解决?

reactjs
1个回答
0
投票

您可以采用2种方法:

首先是设置父选择标签的内部html。像这样的东西:

<select dangerouslySetInnerHTML={this.state.stuff}></select>

这绝对不是我推荐的。由于您的api位于localhost上,因此我假设您能够操纵响应?如果是这样,您是否能够获取api以返回对象数组?像这样的东西:

[{
    "value": "hello",
    "text": "hello"
},
{
    "value": "hello2",
    "text": "hello2"
},
{
    "value": "sss",
    "text": "sss"
}]

然后,您可能会这样:

<select>
    {this.state.stuff.map((o,i) => <option key={i} value={o.value}>{o.text}</option>)}
</select>
© www.soinside.com 2019 - 2024. All rights reserved.