你如何在reactjs中转义报价

时间:2019-02-18 01:03:23

标签: javascript reactjs

我在React应用程序上转义引号时遇到问题。

<textarea id="values" 
          placeholder="{ "name": "John", "test": true}" 
          onChange={this.handleChange2.bind(this)}>
</textarea>

我尝试这样做:

<textarea id="values"
          placeholder="{ \"name\": \"John\", \"test\": true}" 
          onChange={this.handleChange2.bind(this)}>
</textarea> 

但这对我不起作用。

2 个答案:

答案 0 :(得分:0)

尝试改用单引号。

<textarea id="values" 
    placeholder='{ "name": "John", "test": true}'
    onChange={this.handleChange2.bind(this)}>
</textarea>

OR

移动引号{}

<textarea id="values" 
    placeholder={"\"name\": \"John\", \"test\": true"}
    onChange={this.handleChange2.bind(this)}>
</textarea>

答案 1 :(得分:0)

如果要传递值,也可以使用模板文字

// Import these functions and variables to any file that needs to interact with LocalStorage
var storageKeys = ["StorageKostnadVar","StorageLiterVar","StorageDatumVar"];

function addToArray(key, val, arrObj) {
   arrObj[key].push(val)
}

function storeAllLocalStorage(arrayObject) {
    Object.keys(arrayObject).forEach(key=>{
       localStorage.setItem(key, JSON.stringify(arrayObject[key]));
    })
}


// Use above functions when needed
var storedArrays = storageKeys.reduce((acc,key)=> {
      var val = JSON.parse(localStorage.getItem(key));
      if (typeof val === 'array') return {...acc, [key]:val};
      return {...acc, [key]:[val]};
},{})

addToArray("StorageKostnadVar", document.getElementById("tankaKostnad").value, storedArrays);
addToArray("StorageLiterVar", document.getElementById("tankaLiter").value, storedArrays);
addToArray("StorageDatumVar", document.getElementById("tankaDatum").value, storedArrays);

storeAllLocalStorage(storedArrays)