简体   繁体   English

将字符串转换为 JSON 对象以用于 React.js 样式标签 style={}

[英]Convert string to JSON object for use in React.js style tag style={}

I am building a React.js application where I want to allow users to input styles in a text area which will affect the style of another element.我正在构建一个 React.js 应用程序,我希望允许用户在文本区域中输入样式,这将影响另一个元素的样式。

First, I have a row component which looks like this:首先,我有一个如下所示的行组件:

function Row(props) {
  return (
    <tr>
      <td width="50%">
        <textarea 
          style={{}} 
          value={props.style}
          onChange={props.onStyleChange}>
        </textarea>
      </td>
      <td><div className="">Row {props.id+1}</div></td>
    </tr>
  )
}; 

I am iterating through a list of rowData to populate my rows, which can be found here:我正在遍历 rowData 列表以填充我的行,可以在此处找到:

{this.state.rowData.map(function(row, index) {
  return (
    <Row 
        id={row.id} 
        style={row.style} 
        onStyleChange={function(e) {this.onStyleChange(e, row.id)}.bind(this)}/>
          );
}.bind(this))}

Then in my onStyleChange function I have:然后在我的 onStyleChange 函数中,我有:

onStyleChange: function(e, id) {
  this.state.rowData[id].style = e.target.value;
  this.setState(this.state);
}

So as a user enters data into the the textarea, it adds to the i'th element in my rowData array.因此,当用户将数据输入到 textarea 时,它会添加到我的 rowData 数组中的第 i 个元素。 Assuming its the 0th row and the user enters "Hello" into the text area, then rowData[0].style = "Hello".假设它是第 0 行并且用户在文本区域中输入“Hello”,则 rowData[0].style =“Hello”。

However, I would like to be able to do something like this: style={{props.style}} inside my Row component.但是,我希望能够在我的 Row 组件中执行以下操作: style={{props.style}} But because it is currently a string it does not work.但是因为它目前是一个字符串,所以它不起作用。 I have also tried style={JSON.parse(props.style)} which throws an error every time I add a new row because props.style='{}'.我也试过style={JSON.parse(props.style)}每次添加新行时都会抛出错误,因为 props.style='{}'。 The error reads Uncaught SyntaxError: Unexpected token f in JSON at position 1错误读取Uncaught SyntaxError: Unexpected token f in JSON at position 1

Always grateful for any help.永远感谢任何帮助。 There's got to be a much easier way to do this.必须有一种更简单的方法来做到这一点。 Thank you.谢谢你。

Two steps to convert inline-style to object-style` as restricted by React :inline-style to转换为受 React 限制的对象inline-style to两个步骤:

  1. Parse the string to be a JSON object.将字符串解析为 JSON 对象。

  2. Convert the keys of this object to camel case ( z-index becomes zIndex .. so on)将此对象的键转换为驼峰式大小写( z-index变为zIndex .. 依此类推)

Congrats!恭喜! i wrote the algorithm , check below :我写了算法,请检查以下内容:

 const example1= "position:absolute;h-index:9001;" const example2 = "-ms-transform: rotate(20deg);-webkit-transform: rotate(20deg);"; // 2ⁿᵈ step logic const camelize = (string) => string.replace(/-([az])/gi,(s, group) => group.toUpperCase()); // 1ˢᵗ step logic which calls the 2ⁿᵈ step logic const style2object = (style) => style.split(';').filter(s => s.length) .reduce((a, b) => { const keyValue = b.split(':'); a[camelize(keyValue[0])] = keyValue[1] ; return a; } ,{}); console.log("Example 1 : ", example1, '\\n', style2object(example1) ) console.log("Example 2 : ", example2, '\\n', style2object(example2) )

If it is helpful the style attribute needs an object like {"color": "blue"}如果有帮助,样式属性需要一个像 {"color": "blue"} 这样的对象

I made a demo with your code the only thing that escapes me is how to update with the onChange event.我用你的代码做了一个演示,唯一让我失望的是如何使用 onChange 事件进行更新。

function Row(props) {
  const styleValue = JSON.stringify(props.style);
  return (
    <tr>
      <td width="50%">
        <textarea 
          style={props.style} 
          defaultValue={styleValue}
          onChange={props.onStyleChange}/>

      </td>
      <td><div className="">Row {props.id+1}</div></td>
    </tr>
  )
};

class App extends React.Component {
  state = {
    rowData: [{
      id: 1,
      style: {
        color: 'blue'
      }
    }, {
      id: 2,
      style: {
        color: 'red',
        backgroundColor:'#000'
      }
    }]
  };

  onStyleChange(e, id) {
    const rows = this.state.rowData;
    const row = rows.find(row => row.id  === id);
    const index = rows.indexOf(row);
    rows[index]['style'] = JSON.parse(e.target.value);
    this.setState({
      rowData: rows
    });
  }
  render() {
    return (
      <table>
         <tbody>
      {
      this.state.rowData.map(function(row, index) {
        return (
          <Row 
        id={row.id} 
        key={index}
        style={row.style} 
        onStyleChange={function(e) {this.onStyleChange(e, row.id)}.bind(this)}/>
        );
      }.bind(this))

    }
          </tbody>
    </table>
    )
  }
}

ReactDOM.render(<App/>, document.getElementById('app'));

http://codepen.io/GGarciaSeco/pen/vgVEGX?editors=0010 http://codepen.io/GGarciaSeco/pen/vgVEGX?editors=0010

You can take a look to the React documentation in the next link您可以在下一个链接中查看 React 文档

https://facebook.github.io/react/docs/dom-elements.html#style https://facebook.github.io/react/docs/dom-elements.html#style

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

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