这是一个简短的教程,介绍如何在react实例中把字符串转换为数组。它包括如何使用split()函数将带有分隔符的字符串转换为数组。
假设我们有一个字符串作为输入
var mystr="This is an string"
并将输出转换为数组
["this","is","an","string"]
在javascript中,我们有一个字符串split()函数。它被用来将字符串分割成数组字。
下面是一个语法
string.split(delimiter)
默认情况下,分隔符是空格,可以包括逗号(,)、连字符(-)和任何字符。
在实时情况下,我们有一个来自API的对象。这个对象包含了一个字符串的属性,我们需要将其转换为数组,以便在反应中的组件中呈现。
让我们看看在react中使用不同分隔符空格或逗号的例子。
如何在react javascript中把字符串转换为带空格的数组
这个例子将存储在react状态下的字符串转换成数组。
- 将字符串存储在react状态中
- 在Render方法中,使用split方法将字符串转换成带有分隔符空格的数组。
- 最后使用map迭代将数组渲染成组件上的有序列表。
例子。
import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
interface AppProps {}
interface AppState {
name: string;
}
class App extends Component {
constructor(props) {
super(props);
this.state = {
name: 'This is an string'
};
}
render() {
let str = this.state.name;
var myarray = str.split(' ');
console.log(myarray);
let result = myarray.map(item => {item});
return (
{result}
);
}
}
如何在react中把带有逗号分隔符的字符串转换为数组
这是一个将全名转换为名、姓、中间名数组的例子。
- 让我们把全名用字符串分隔符存储在react组件的状态中。
- 使用字符串定界符将字符串转换为数组
- 最后使用map函数将字符串数组打印到渲染器中。
import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
interface AppProps {}
interface AppState {
name: string;
}
class App extends Component {
constructor(props) {
super(props);
this.state = {
name: 'firstName, lastName, middleName'
};
}
render() {
let fullname = this.state.name;
var names = fullname.split(',');
let result = names.map(item => {item});
return (
{result}
);
}
}
render(, document.getElementById('root'));
结论
在这个例子中,我们用react中的数组分割函数将字符串转换成带有空格或分隔符的数组.