本文将为您提供关于classList.add仅在ReactJs中首次工作的详细介绍,我们还将为您解释react的class的相关知识,同时,我们还将为您提供关于classList介绍和原生JavaSc
本文将为您提供关于classList.add仅在ReactJs中首次工作的详细介绍,我们还将为您解释react的class的相关知识,同时,我们还将为您提供关于classList介绍和原生JavaScript实现addClass、removeClass等、javascript – 在ReactJs中使用GoJs、js实现addClass方法,classList与className有什么区别?、reactjs – BrowserslistError:React / Express App中未知的浏览器查询`dead`的实用信息。
本文目录一览:- classList.add仅在ReactJs中首次工作(react的class)
- classList介绍和原生JavaScript实现addClass、removeClass等
- javascript – 在ReactJs中使用GoJs
- js实现addClass方法,classList与className有什么区别?
- reactjs – BrowserslistError:React / Express App中未知的浏览器查询`dead`
classList.add仅在ReactJs中首次工作(react的class)
如果您的浏览器堆栈允许,则可以使用:focus-within
伪类来实现相同的行为。
您只需要li:focus-within { outline: 2px solid blue }
classList介绍和原生JavaScript实现addClass、removeClass等
使用jQuery可以给元素很方便的添加class和删除class等操作,现在原生的JavaScript也可以实现这个方法了。使用classList可以方便的添加class、删除class、查询class等。
语法:
let elementClass = element.classList;
elementClasses 是一个 DOMTokenList 表示 element 的类属性 。如果类属性未设置或为空,那么 elementClasses.length 返回 0。element.classList 本身是只读的,虽然你可以使用 add() 和 remove() 方法修改它。
方法:
add( String [, String] )
添加指定的类值。如果这些类已经存在于元素的属性中,那么它们将被忽略。
remove( String [,String] )
删除指定的类值。
item ( Number )
按集合中的索引返回类值。
toggle ( String [, force] )
当只有一个参数时:切换 class value; 即如果类存在,则删除它并返回false,如果不存在,则添加它并返回true。
当存在第二个参数时:如果第二个参数的计算结果为true,则添加指定的类值,如果计算结果为false,则删除它
contains( String )
检查元素的类属性中是否存在指定的类值。
示例:
// div是具有class =“foo bar”的<div>元素的对象引用
div.classList.remove("foo");
div.classList.add("anotherclass");
// 如果visible被设置则删除它,否则添加它
div.classList.toggle("visible");
// 添加/删除 visible,取决于测试条件,i小于10
div.classList.toggle("visible", i < 10);
alert(div.classList.contains("foo"));
//添加或删除多个类
div.classList.add("foo","bar");
div.classList.remove("foo", "bar");
兼容性:
不兼容Android2.3和iOS4.2的,在移动端上想使用也是有点头疼啊。IE系列的更别说IE9和IE8了。所以目前来看,还是无法在实际中放心的使用,只能用于某些特定的项目等。不过我们可以通过一些shim来实现,或者最下方给出的原生javascript实现。
跨浏览器javascript shim
https://github.com/eligrey/cl...
原生JavaScript
类似于jQuery库的使用方式,使用className通过正则来添加或者删除class。
addClass、removeClass、toggleClass、hasClass
function hasClass(obj, cls) {
return obj.className.match(new RegExp(''(\\s|^)'' + cls + ''(\\s|$)''));
}
function addClass(obj, cls) {
if (!this.hasClass(obj, cls)) obj.className += " " + cls;
}
function removeClass(obj, cls) {
if (hasClass(obj, cls)) {
var reg = new RegExp(''(\\s|^)'' + cls + ''(\\s|$)'');
obj.className = obj.className.replace(reg, '' '');
}
}
function toggleClass(obj,cls){
if(hasClass(obj,cls)){
removeClass(obj, cls);
}else{
addClass(obj, cls);
}
}
参考链接:
https://blog.csdn.net/leadn/a...
javascript – 在ReactJs中使用GoJs
<!DOCTYPE html> <html> <head> <title>Parse Tree</title> <Meta name="description" content="A collapsible tree layout with all of the leaf nodes at the same layer." /> <!-- copyright 1998-2016 by northwoods Software Corporation. --> <Meta charset="UTF-8"> <script src="go.js"></script> <link href="../assets/css/goSamples.css" rel="stylesheet" type="text/css" /> <!-- you don't need to use this --> <script src="goSamples.js"></script> <!-- this is only for the GoJS Samples framework --> <script id="code"> function init() { if (window.goSamples) goSamples(); // init for these samples -- you don't need to call this var $= go.GraphObject.make; // for conciseness in defining templates myDiagram = $(go.Diagram,"myDiagramDiv",{ allowcopy: false,allowDelete: false,allowMove: false,initialContentAlignment: go.Spot.Center,initialAutoScale: go.Diagram.Uniform,layout: $(FlatTreeLayout,// custom Layout,defined below { angle: 90,compaction: go.TreeLayout.CompactionNone }),"undoManager.isEnabled": true }); myDiagram.nodeTemplate = $(go.Node,"Vertical",{ selectionObjectName: "BODY" },$(go.Panel,"Auto",{ name: "BODY" },$(go.Shape,"RoundedRectangle",new go.Binding("fill"),new go.Binding("stroke")),$(go.TextBlock,{ font: "bold 12pt Arial,sans-serif",margin: new go.Margin(4,2,2) },new go.Binding("text")) ),// this is underneath the "BODY" { height: 15 },// always this height,even if the TreeExpanderButton is not visible $("TreeExpanderButton") ) ); myDiagram.linkTemplate = $(go.Link,{ strokeWidth: 1.5 })); // set up the nodeDataArray,describing each part of the sentence var nodeDataArray = [ { key: 1,text: "Sentence",fill: "#f68c06",stroke: "#4d90fe" },{ key: 2,text: "NP",stroke: "#4d90fe",parent: 1 },{ key: 3,text: "DT",fill: "#ccc",parent: 2 },{ key: 4,text: "A",fill: "#f8f8f8",parent: 3 },{ key: 5,text: "JJ",{ key: 6,text: "rare",parent: 5 },{ key: 7,{ key: 8,text: "black",parent: 7 },{ key: 9,text: "NN",{ key: 10,text: "squirrel",parent: 9 },{ key: 11,text: "VP",{ key: 12,text: "VBZ",parent: 11 },{ key: 13,text: "has",parent: 12 },{ key: 14,{ key: 15,text: "VBN",parent: 14 },{ key: 16,text: "become",parent: 15 },{ key: 17,{ key: 18,parent: 17 },{ key: 19,parent: 18 },{ key: 20,text: "a",parent: 19 },{ key: 21,{ key: 22,text: "regular",parent: 21 },{ key: 23,{ key: 24,text: "visitor",parent: 23 },{ key: 25,text: "PP",{ key: 26,text: "TO",parent: 25 },{ key: 27,text: "to",parent: 26 },{ key: 28,{ key: 29,parent: 28 },{ key: 30,parent: 29 },{ key: 31,{ key: 32,text: "suburban",parent: 31 },{ key: 33,{ key: 34,text: "garden",parent: 33 },{ key: 35,text: ".",{ key: 36,parent: 35 } ] // create the Model with data for the tree,and assign to the Diagram myDiagram.model = $(go.TreeModel,{ nodeDataArray: nodeDataArray }); } // Customize the TreeLayout to position all of the leaf nodes at the same vertical Y position. function FlatTreeLayout() { go.TreeLayout.call(this); // call base constructor } go.Diagram.inherit(FlatTreeLayout,go.TreeLayout); // This assumes the TreeLayout.angle is 90 -- growing downward /** @override */ FlatTreeLayout.prototype.commitLayout = function() { go.TreeLayout.prototype.commitLayout.call(this); // call base method first // find maximum Y position of all Nodes var y = -Infinity; this.network.vertexes.each(function(v) { y = Math.max(y,v.node.position.y); }); // move down all leaf nodes to that Y position,but keeping their X position this.network.vertexes.each(function(v) { var node = v.node; if (node.isTreeLeaf) { node.position = new go.Point(node.position.x,y); } }); }; // end FlatTreeLayout </script> </head> <body onload="init()"> <div id="sample"> <h3>GoJS Parse Tree</h3> <div id="myDiagramDiv"></div> <p>A <em>parse tree</em> is an ordered,rooted tree representing the structure of a sentence,broken down to parts-of-speech.</p> <p> This diagram uses a custom <a>TreeLayout</a> called <b>FlatTreeLayout</b> that places all leaf nodes at the same Y position. It also makes use of a <b>TreeExpanderButton</b> on the node template. See the <a href="../intro/buttons.html">Intro page on Buttons</a> for more GoJS button information. </p> <p> The abbreviations used in this diagram are: <ul> <li><b>NP</b>,a noun phrase</li> <li><b>VP</b>,a verb phrase</li> <li><b>PP</b>,a prepositional phrase</li> <li><b>DT</b>,a determiner</li> <li><b>JJ</b>,an adjective</li> <li><b>NN</b>,a common noun</li> <li><b>VBZ</b>,a third person singular present verb</li> <li><b>VBN</b>,a past participle verb</li> </ul> </p> </div> </body> </html>
这个我尝试使用它时得到的代码作出反应
import React,{Component} from 'react'; import go from 'gojs'; const goObj = go.GraphObject.make; export default class GoJs extends Component { constructor (props) { super (props); this.renderCanvas = this.renderCanvas.bind (this); this.state = {myModel: null,myDiagram: null} } renderCanvas () { let model = goObj (go.TreeModel); let diagram = goObj (go.Diagram,this.refs.goJsDiv,{initialContentAlignment: go.Spot.Center}); this.setState({myModel: model,myDiagram: diagram},() => { model.nodeDataArray = this.props.data; diagram.model = model; this.setState({myModel: model,myDiagram: diagram}); } ); } componentDidMount () { this.renderCanvas (); } componentwillUpdate (prevProps) { if (this.props.data !== prevProps.data) { console.log ('Updating'); const model = this.state.myModel; const diagram = this.state.myDiagram; model.nodeDataArray = this.props.data; diagram.model = model; this.setState({myModel: model,myDiagram: diagram}); } } render () { return <div ref="goJsDiv" style={{'width': '500px','height': '500px','backgroundColor': '#DAE4E4'}}></div>; } } GoJs.propTypes = { data: React.PropTypes.string.isrequired }; GoJs.defaultProps = { data: '[]' };
我无法弄清楚什么是丢失的,而我从这里得到的输出是一团糟.
解决方法
import React,myDiagram: null} } renderCanvas () { function FlatTreeLayout () { go.TreeLayout.call(this); // call base constructor } go.Diagram.inherit(FlatTreeLayout,go.TreeLayout); // This assumes the TreeLayout.angle is 90 -- growing downward /** @override */ FlatTreeLayout.prototype.commitLayout = function () { go.TreeLayout.prototype.commitLayout.call(this); // call base method first // find maximum Y position of all Nodes var y = -Infinity; this.network.vertexes.each(function(v) { y = Math.max(y,v.node.position.y); }); // move down all leaf nodes to that Y position,but keeping their X position this.network.vertexes.each(function(v) { var node = v.node; if (node.isTreeLeaf) { node.position = new go.Point(node.position.x,y); } }); }; let model = goObj (go.TreeModel); let diagram = goObj (go.Diagram,{ allowcopy: false,layout: goObj(FlatTreeLayout,defined below { angle: 90,"undoManager.isEnabled": true }); diagram.nodeTemplate = goObj(go.Node,goObj(go.Panel,goObj(go.Shape,goObj(go.TextBlock,new go.Binding("text")) ),// this is underneath the "BODY" { height: 15 },even if the TreeExpanderButton is not visible goObj("TreeExpanderButton") ) ); diagram.linkTemplate = goObj(go.Link,{ strokeWidth: 1.5 })); this.setState({myModel: model,myDiagram: diagram}); } ); } componentDidMount () { this.renderCanvas (); } componentwillUpdate (prevProps) { if (this.props.data !== prevProps.data) { console.log ('Updating'); const model = this.state.myModel; const diagram = this.state.myDiagram; model.nodeDataArray = this.props.data; diagram.model = model; this.setState({myModel: model,'backgroundColor': '#DAE4E4'}}></div>; } } GoJs.propTypes = { data: React.PropTypes.string.isrequired }; GoJs.defaultProps = { data: '[]' };
由于它是一个dum组件,我们必须通过props从父组件传递数据.
来自父组件
render(){ return( <div> <PTagBox data={nodeDataArray}/> </div> ); }
其中PTagBox是哑或子组件
js实现addClass方法,classList与className有什么区别?
壹 ❀ 引
贰 ❀ 从classList属性入手
我们随便获取一个dom对象,打印出它的对象属性,可以看到管理class类的主要有classList属性与className属性,我们先从classList属性下手。
1.classList属性
classList属性的值为DOMTokenList对象,关于DOMTokenList官方解释是一组空格分隔的标记,与Array一样具有length属性,且索引从0开始,但无法使用Array对象的方法。
不过DOMTokenList对象内置了add,remove,contains等方法,用于增删改查等操作;所以我们可以使用add,remove像JQ中addClass与removeClass方法一样操作class类。
let div = document.querySelector(''div'');
div.classList.add("newClass");
div.classList.remove("newClass");
2.classList兼容问题
我们发现这两个方法用的很爽啊,跟JQ一样,一个方法解决class类的操作,但比较遗憾的是,这两个方法均存在兼容问题:
虽然其它浏览器兼容性良好,但铁打的IE从9之前完全不支持classList属性,从版本10开始支持该属性,但不支持add与remove方法。
所以说如果要兼容IE,此做法不可取,但如果不用考虑IE,那就真的能像JQ一样使用便捷了。
叁 ❀ 从className属性入手
1.className与classList的区别
说完classList属性,我们再考虑从className下手;className属性与classList属性同为Dom属性且都管理class类的值,不同的是classList属性值为特殊的DOMTokenList对象,而className属性的值为普通的字符串。
我们尝试自定义一个有class类的元素,分别获取两者的值:
<div></div>
2.用js模拟实现
那要从className属性入手来操作class类,无非就是字符串的拼接截取操作了,这里就直接附上代码:
//自定义添加class方法
function addClass(ele, name) {
if (name) {
//判断该dom有没有class,有则在原class基础上增加,无则直接赋值
ele.className ? ele.className = ele.className + " " + name : ele.className = name;
} else {
throw new Error("请传递一个有效的class类名");
};
};
//自定义删除class类方法
function removeClass(ele, name) {
//将className属性转为数组
let classArr = ele.className.split(" "),
index = classArr.indexOf(name);
//将符合条件的class类删除
index > -1 ? classArr.splice(index, 1) : null;
ele.className = classArr.join(" ");
};
let div = document.querySelector(''div'');
//测试调用
addClass(div, ''demo1'');
removeClass(div, ''demo1'');
我在网上也看了下别人的方案,对于removeClass,我这里使用的是转成数组后利用splice删除传递的class类后,再转成字符串赋给className属性,可能有点繁琐。其他人的方案大部分是通过正则匹配替换,再去掉多余空格,但是我的正则是真的挺烂...
本文只是作为一个简单思路记忆,毕竟我第一点确实想到用classList去做操作,而且天真的以为classList是一个类数组,结果失败了..
那么就记录到这里了!
reactjs – BrowserslistError:React / Express App中未知的浏览器查询`dead`
> workout_tracker@0.1.0 build /Users/*******/mern-workout/client > react-scripts build Creating an optimized production build... Failed to compile. ./src/Components/UI/Spinner/Spinner.module.css Module build Failed: browserslistError: UnkNown browser query `dead` at Array.forEach (<anonymous>) npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! workout_tracker@0.1.0 build: `react-scripts build` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the workout_tracker@0.1.0 build script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! /Users/*******/.npm/_logs/2018-10-22T23_21_04_691Z-debug.log
我已经搜索了,但是,唯一的解决方案似乎是使用Angular的人,他们的Bootstrap版本存在一些问题.我没有在我的应用程序中使用Bootstrap.
我试图从browserslist数组中删除“not dead”只是为了看看会发生什么,我得到了这个:
Creating an optimized production build... Failed to compile. Failed to minify the code from this file: ./node_modules/query-string/index.js:8 npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! workout_tracker@0.1.0 build: `react-scripts build` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the workout_tracker@0.1.0 build script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! /Users/******/.npm/_logs/2018-10-22T23_41_55_488Z-debug.log
这是我的package.json文件:
{ "name": "workout_tracker","version": "0.1.0","private": true,"dependencies": { "axios": "^0.18.0","browserslist": "^4.3.1","cssnano": "^4.1.7","firebase": "^5.3.0","jw-paginate": "^1.0.2","jw-react-pagination": "^1.0.7","normalize.css": "^8.0.0","query-string": "^6.2.0","random-id": "0.0.2","react": "^16.5.2","react-dom": "^16.5.2","react-headroom": "^2.2.2","react-icons-kit": "^1.1.6","react-redux": "^5.0.7","react-router-dom": "^4.3.1","react-scripts-cssmodules": "^1.1.10","react-swipe-to-delete-component": "^0.3.4","react-swipeout": "^1.1.1","redux": "^4.0.0","redux-thunk": "^2.3.0" },"scripts": { "start": "react-scripts start","build": "react-scripts build","test": "react-scripts test --env=jsdom","eject": "react-scripts eject" },"devDependencies": { "css-loader": "^1.0.0","redux-devtools-extension": "^2.13.5","webpack": "^3.8.1" },"browserslist": [ ">0.2%","not dead","not ie <= 11","not op_mini all" ],"proxy": "http://localhost:4000" }
解决方法
如果您打开上面的../browserlist/index.js文件,您会看到:
var QUERIES = [ { regexp: /^last\s+(\d+)\s+major versions?$/i,select: function (context,versions) ... },...,]
您可以在其中添加以下内容:
{ regexp: /^dead$/i,select: function (context) { var dead = [''ie <= 10'',''ie_mob <= 10'',''bb <= 10'',''op_mob <= 12.1''] return resolve(dead,context) } }
这对我来说没有改变package-json.lock中的依赖版本
我们今天的关于classList.add仅在ReactJs中首次工作和react的class的分享已经告一段落,感谢您的关注,如果您想了解更多关于classList介绍和原生JavaScript实现addClass、removeClass等、javascript – 在ReactJs中使用GoJs、js实现addClass方法,classList与className有什么区别?、reactjs – BrowserslistError:React / Express App中未知的浏览器查询`dead`的相关信息,请在本站查询。
本文标签: