Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save xyzdata/5acc4a357722e9e2636009fbd6846338 to your computer and use it in GitHub Desktop.
Save xyzdata/5acc4a357722e9e2636009fbd6846338 to your computer and use it in GitHub Desktop.
dynamically-add-child-components-in-react

dynamically-add-child-components-in-react

https://stackoverflow.com/questions/36651583/dynamically-add-child-components-in-react

    
var App = require('./App.js');
var SampleComponent = require('./SampleComponent.js');
ReactDOM.render(
    <App>
        <SampleComponent name="SomeName"/> 
    <App>, 
    document.body
);
    
var App = React.createClass({
    render: function() {
        return (
            <div>
                <h1>App main component! </h1>
                {
                    this.props.children
                }
            </div>
        );
    }
});
    
var App = React.createClass({

    getInitialState: function(){
        return [
            {id:1,name:"Some Name"}
        ]
    },

    addChild: function() {
        // State change will cause component re-render
        this.setState(this.state.concat([
            {id:2,name:"Another Name"}
        ]))
    }

    render: function() {
        return (
            <div>
                <h1>App main component! </h1>
                <button onClick={this.addChild}>Add component</button>
                {
                    this.state.map((item) => (
                        <SampleComponent key={item.id} name={item.name}/>
                    ))
                }
            </div>
        );
    }

});
@xyzdata
Copy link
Author

xyzdata commented Jun 26, 2017

React components & react-router-dom

props & route.data

const cars = this.props.route.data;

https://gist.github.com/xgqfrms-gildata/1d912ebf4045f9dcc0747cb761f62090

@xyzdata
Copy link
Author

xyzdata commented Jun 26, 2017

https://react-app.xgqfrms.xyz

Application: react-app
Key: 5supkkkr2jzk5msdafg8syr8
Secret: xfV7mAt4hUWE6TupJQdwyWmR

Key Rate Limits

5	Calls per second
25	Calls per day

http://edmunds.mashery.com/apps/mykeys

http://edmunds.mashery.com/docs

@xyzdata
Copy link
Author

xyzdata commented Jun 26, 2017

css-loader & style-loader

$ npm i -D css-loader style-loader

$ npm install --save-dev css-loader style-loader

import 'bootstrap/dist/css/bootstrap.css';

module.exports = {
    module: {
        rules: [{
            test: /\.css$/,
            use: [ 'style-loader', 'css-loader' ]
        }]
    }
}

https://webpack.js.org/guides/code-splitting-css/

@xyzdata
Copy link
Author

xyzdata commented Jun 26, 2017

webpack style-loader!css-loader

input-value object-length & github gist API

https://gist.github.com/xgqfrms-GitHub/c270a295bf3972cdba2977846b3b4689

@xyzdata
Copy link
Author

xyzdata commented Jun 26, 2017

@xyzdata
Copy link
Author

xyzdata commented Jun 26, 2017

@xgqfrms-GitHub
Copy link

xgqfrms-GitHub commented Jun 26, 2017

webpack 3 & lazy-load-react

https://webpack.js.org/guides/lazy-load-react/

<LazilyLoad modules={{
    TodoHandler: () => importLazy(import('./components/TodoHandler')),
    TodoMenuHandler: () => importLazy(import('./components/TodoMenuHandler')),
    TodoMenu: () => importLazy(import('./components/TodoMenu')),
}}>
{({TodoHandler, TodoMenuHandler, TodoMenu}) => (
    <TodoHandler>
        <TodoMenuHandler>
            <TodoMenu />
        </TodoMenuHandler>
    </TodoHandler>
)}
</LazilyLoad>

@xgqfrms-GitHub
Copy link

xgqfrms-GitHub commented Jun 26, 2017

webpack 3 china

https://doc.webpack-china.org/

https://doc.webpack-china.org/guides/lazy-load-react/

<LazilyLoad modules={{
    TodoHandler: () => importLazy(import('./components/TodoHandler')),
    TodoMenuHandler: () => importLazy(import('./components/TodoMenuHandler')),
    TodoMenu: () => importLazy(import('./components/TodoMenu')),
}}>
{({TodoHandler, TodoMenuHandler, TodoMenu}) => (
    <TodoHandler>
        <TodoMenuHandler>
            <TodoMenu />
        </TodoMenuHandler>
    </TodoHandler>
)}
</LazilyLoad>



<LazilyLoad modules={{
    TodoHandler: () => import('./components/TodoHandler'),
    TodoMenuHandler: () => import('./components/TodoMenuHandler'),
    TodoMenu: () => import('./components/TodoMenu'),
}}>
    {({TodoHandler, TodoMenuHandler, TodoMenu}) => (
        <TodoHandler>
            <TodoMenuHandler>
                <TodoMenu />
            </TodoMenuHandler>
        </TodoHandler>
    )}
</LazilyLoad>

@xgqfrms-GitHub
Copy link

xgqfrms-GitHub commented Jun 26, 2017

webpack 2/3 生产环境构建

https://doc.webpack-china.org/guides/production/

$ webpack -p 


$ webpack --optimize-minimize --define process.env.NODE_ENV="production"

webpack loader-options-plugin

https://doc.webpack-china.org/plugins/loader-options-plugin/

new webpack.LoaderOptionsPlugin({
    minimize: true,
    debug: false,
    options: {
        context: __dirname
    }
}),

UglifyJsPlugin

webpack 自带了 UglifyJsPlugin

https://doc.webpack-china.org/guides/production/#js-

http://lisperator.net/uglifyjs/

https://github.com/mishoo/UglifyJS2/

http://marijn.haverbeke.nl/uglifyjs

https://github.com/mishoo/UglifyJS

@xgqfrms-GitHub
Copy link

@xgqfrms-GitHub
Copy link

xgqfrms-GitHub commented Jun 26, 2017

configuration

https://webpack.js.org/configuration/

https://webpack.js.org/configuration/module/

https://webpack.js.org/concepts/loaders/

module.exports = {
    module: {
        rules: [
            {
                test: /\.css$/,
                use: 'css-loader'
            },
            {
                test: /\.ts$/,
                use: 'ts-loader'
            }
        ]
    }
};



{
    test: /\.css$/,
    loader: 'css-loader'
}
// or equivalently
{
    test: /\.css$/,
    use: 'css-loader'
}
// or equivalently
{
    test: /\.css$/,
    use: {
        loader: 'css-loader',
        options: {
            /**/ 
        }
    }
}



{
    test: /\.css$/,
    use: [
        {
            loader: 'style-loader'
        }, 
        {
            loader: 'css-loader',
            options: {
                modules: true
            }
        }
    ]
}


{
    test: /\.scss$/,
    use: [
        {
            loader: 'style-loader'
        }, 
        {
            loader: 'css-loader',
            options: {
                modules: true
            }
        },
        {
            loader: 'sass-loader'
        }
    ]
}



@xgqfrms-GitHub
Copy link

https://webpack.js.org/guides/code-splitting-css/

module.exports = {
    module: {
        rules: [
            {
                test: /\.css$/,
                use: ['style-loader', 'css-loader']
            },
            {
                test: /\.scss$/,
                use: ['style-loader', 'css-loader', 'sass-loader']
            }
        ]
    }
}




module.exports = {
    module: {
        rules: [
            {
                test: /\.css$/,
                use: ExtractTextPlugin.extract({
                    use: 'css-loader'
                })
            }
        ]
    },
    plugins: [
        new ExtractTextPlugin('styles.css'),
    ]
}

import 'bootstrap/dist/css/bootstrap.css';

$ npm i -D  css-loader style-loader sass-loader extract-text-webpack-plugin


$ yarn add -D  css-loader style-loader sass-loader extract-text-webpack-plugin


$ npm install --save-dev css-loader style-loader sass-loader

$ npm install --save-dev extract-text-webpack-plugin


css-loader & style-loader & sass-loader

https://webpack.js.org/loaders/css-loader/

https://webpack.js.org/loaders/style-loader/

sass-loader

https://webpack.js.org/guides/asset-management/#loading-images

https://webpack.js.org/guides/asset-management/#loading-data

https://robertknight.github.io/posts/webpack-dll-plugins/

loaders

https://webpack.js.org/loaders/

https://webpack.js.org/loaders/url-loader/

https://webpack.js.org/loaders/file-loader/

https://webpack.js.org/loaders/sass-loader/

https://webpack.js.org/loaders/worker-loader/

https://webpack.js.org/loaders/json-loader/

Since webpack v2, importing of JSON files will work by default.
You might still want to use this if you use a custom file extension.

由于webpack v2,导入JSON文件将默认工作。
如果您使用自定义文件扩展名,您可能仍然希望使用此选项。

https://webpack.js.org/loaders/json5-loader/

http://json5.org/

https://github.com/json5/json5

{
    foo: 'bar',
    while: true,

    this: 'is a \
multi-line string',

    // this is an inline comment
    here: 'is another', // inline comment

    /* this is a block comment
       that continues on another line */

    hex: 0xDEADbeef,
    half: .5,
    delta: +10,
    to: Infinity,   // and beyond!

    finally: 'a trailing comma',
    oh: [
        "we shouldn't forget",
        'arrays can have',
        'trailing commas too',
    ],
}

https://github.com/json5/json5/blob/master/package.json5

https://webpack.js.org/loaders/html-loader/

https://webpack.js.org/loaders/gzip-loader/

yarn add

https://yarnpkg.com/zh-Hans/docs/cli/add

https://yarnpkg.com/zh-Hans/docs/cli/install

$ yarn add

$ yarn add [--dev/-D]

$ yarn add [--peer/-P]

$ yarn add [--optional/-O]

$ yarn add [--exact/-E]

$ yarn add [--tilde/-T]

@xgqfrms-GitHub
Copy link

xgqfrms-GitHub commented Jun 27, 2017

const data = [
    {"id": "1", "name": "name_1", "parent_id": "0", "depth": "0"},
    {"id": "2", "name": "name_2", "parent_id": "0", "depth": "0"},
    {"id": "3", "name": "name_3", "parent_id": "1", "depth": "1"},
    {"id": "4", "name": "name_4", "parent_id": "3", "depth": "2"}
];


function getMenu(parentID){
    const cc = {
        "color": "red",
        "font-size": "32px"
    };
    JSON.stringify(cc);
    // "{"color":"red","font-size":"32px"}"
    let style = `
        color: rgba(0,2555,0,0.7);
        font-size: 32px;
        border: 1px solid red;
        background: #000;
    `;
    return (
        data.filter(
            function(node){
                console.log(`%c nodes = `, `${style}`, node);
                return node.parent_id === parentID;
            }
        ).map(
            function(node){
                var exists = data.some(
                    function(childNode){
                        console.log(`%c childNode = `, `${style}`, node);
                        return childNode.parent_id === node.id;
                    }
                );
                // recursive
                /* A recursive function (DEF) is a function which either calls itself or is in a potential cycle of function calls. */
                let subMenu = exists ? `<ul> ${getMenu(node.id).join('')} </ul>` : ``;
                return `<li> ${node.name} ${subMenu} </li>`;
            }
        )
    );
}


var initLevel = 0;

var endMenu =getMenu("0");

console.log(`<ul> ${endMenu.join('')} </ul>`);


/*
<ul>
    <li> name_1
        <ul>
            <li> name_3
                <ul>
                    <li> name_4 </li>
                </ul>
            </li>
        </ul>
    </li>
    <li> name_2 </li>
</ul>
*/


https://gist.github.com/xyzdata/50d9af7fe5749fe199146e4e5e2f3f1e#gistcomment-2133425

@xgqfrms-GitHub
Copy link

xgqfrms-GitHub commented Jun 27, 2017

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some

some() 方法测试数组中的某些元素是否通过由提供的函数实现的测试。

var newArray = arr.filter(callback[, thisArg]);

const isBiggerThan10 = (element, index, array) => {
  return element > 10;
}

[2, 5, 8, 1, 4].some(isBiggerThan10);  
// false

[12, 5, 8, 1, 4].some(isBiggerThan10); 
// true

callback 被调用时传入三个参数:元素的值,元素的索引,被遍历的数组。

function callback(element, index, array) {}

@xgqfrms-GitHub
Copy link

object.keys-object[keys]

const data = [
    {"id": "1", "name": "name_1", "parent_id": "0", "depth": "0"},
    {"id": "2", "name": "name_2", "parent_id": "0", "depth": "0"},
    {"id": "3", "name": "name_3", "parent_id": "1", "depth": "1"},
    {"id": "4", "name": "name_4", "parent_id": "3", "depth": "2"}
];

let object = data[0];

for (let key in object) {
    if (object.hasOwnProperty(key)) {
        console.log(`key = ${key}`);
        let key1 = object.key;
        let key2 = object[key];
        console.log(`object.${key} = ${key1}`);
        console.log(`object[${key}] = ${key2}`);
    }
}
url = `https://cdn.xgqfrms.xyz/json/datalist.json`;

fetch(url)
.then((response) => response.json())
.then((json)=> {
    console.log(`json = ${json}`);
    let obj_length = Object.keys(json).length;
    console.log(`json length = ${obj_length}`);
    return repos = json;
})
.then((repos)=>{
    console.log(`repos.length = ${Object.keys(repos).length}`);
    array.forEach(function(element) {
        // 
    }, this);
    for (let key in object) {
        if (object.hasOwnProperty(key)) {
            console.log(`key = ${key}`);
            let key1 = object.key;
            let key2 = object[key];
            console.log(`object.${key} = ${key1}`);
            console.log(`object[${key}] = ${key2}`);
        }
    }
    for (let key in object) {
        if (object.hasOwnProperty(key)) {
            let element = object[key];
            console.log(`object.${key} = ${element}`);
        }
    }
    for (var index = 0; index < array.length; index++) {
        var element = array[index];
        
    }
    console.log(`id = ${repos[0].id}`);
    console.log(`name = ${repos[0].name}`);
    console.log(`isParent = ${repos[0].isParent}`);
});

@xgqfrms-GitHub
Copy link

js-get-html5-input-value
object keys-object keys
array slice
new window url

@xgqfrms-GitHub
Copy link

@xgqfrms-GitHub
Copy link

xgqfrms-GitHub commented Jun 27, 2017

github API

let username = `xgqfrms-GitHub`;
    repo = `Node-CLI-Tools/commits`;


const url = `https://api.github.com/repos/${username}/${repo}`;

// https://api.github.com/repos/xgqfrms-GitHub/Node-CLI-Tools/commits

// Error API: https://api.github.com/users/${username}/${repo}


fetch(`https://api.github.com/repos/${username}/${repo}`,{
    data: {
        client_id: '08ecc2f68d922f18800e',
        client_secret: '5846d428b5340812b76c9637eceaee979340b922'
    }
})
.then((response) => response.json())
.then((json)=> {
    console.log(`json = ${json}`);
    return repos = json;
})
.then((repos)=>{
    console.log(`repos = ${repos}`);
    console.log(`repos = ${repos.length}`);
    console.log(`repos$ 0  = ${repos[0]}`);
    console.log(`repos$ 1  = ${repos[1]}`);
    for (let i = 0; i < repos.length; i++) {
        console.log(`repos${i}  = ${repos[i]}`);
    }
});

// https://api.github.com/users/xgqfrms

// https://api.github.com/users/xgqfrms/react2 ???





let nct = ((username=`xgqfrms-GitHub`, repo=`Node-CLI-Tools`) => {
    fetch(`https://api.github.com/repos/${username}/${repo}/commits`,{
        data: {
            client_id: '08ecc2f68d922f18800e',
            client_secret: '5846d428b5340812b76c9637eceaee979340b922'
        }
    })
    .then((response) => response.json())
    .then((json)=> {
        return repos = json;
    })
    .then((repos)=>{
        console.log(repos);
    });
})();


/*

API

https://developer.github.com/v3/repos/

https://developer.github.com/v3/users/

https://developer.github.com/v3/repos/#list-user-repositories

https://developer.github.com/v3/repos/#list-organization-repositories

*/

fetch(`https://api.github.com/orgs/webgeeker/repos/`,{
    data: {
        client_id: '08ecc2f68d922f18800e',
        client_secret: '5846d428b5340812b76c9637eceaee979340b922'
    }
})
.then((response) => response.json())
.then((json)=> {
    console.log(`json = ${json}`);
    return repos = json;
});





fetch(`https://api.github.com/users`,{
    data: {
        client_id: '08ecc2f68d922f18800e',
        client_secret: '5846d428b5340812b76c9637eceaee979340b922'
    }
})
.then((response) => response.json())
.then((json)=> {
    console.log(`json = ${json}`);
    return repos = json;
});




fetch(`https://api.github.com/users/xyzdata`,{
    data: {
        client_id: '08ecc2f68d922f18800e',
        client_secret: '5846d428b5340812b76c9637eceaee979340b922'
    }
})
.then((response) => response.json())
.then((json)=> {
    console.log(`json = ${json}`);
    return repos = json;
});













@xgqfrms-GitHub
Copy link

@xgqfrms-GitHub
Copy link

xgqfrms-GitHub commented Jun 27, 2017

@xgqfrms-GitHub
Copy link

xgqfrms-GitHub commented Jun 27, 2017

MDN

let url = `https://raw.githubusercontent.com/xyzdata/json/master/datas/ntb-F9/csjj-old.json`;

fetch(url)
.then((response) => response.json())
.then((json)=> {
    console.log(`json = ${json}`);
    return repos = json;
})
.then((repos)=>{
    console.log(`repos = ${repos}`);
    // Object.keys(myArray).length
    console.log(`json.length = ${Object.keys(repos).length}`);
    console.log(`Button = ${repos.ToolBar.Button[0]}`);
    console.log(`Button = ${repos.ToolBar.Button[1]}`);
    // "@name"
    // @json-error.json
    let name = "@name";
    console.log(`name = ${repos.name}`);
});



url = `https://raw.githubusercontent.com/xyzdata/json/master/datas/ntb-F9/csjj.json`;

fetch(url)
.then((response) => response.json())
.then((json)=> {
    console.log(`json = ${json}`);
    return repos = json;
})
.then((repos)=>{
    console.log(`repos = ${repos}`);
    // Object.keys(myArray).length
    console.log(`json.length = ${Object.keys(repos).length}`);
    console.log(`Button[0] = ${repos.ToolBar.Button[0]}`);
    console.log(`ToolBar.Button[1].name = ${repos.ToolBar.Button[1].name}`);
    console.log(`ToolBar.Button[1].Captio = ${repos.ToolBar.Button[1].Caption}`);
    console.log(`name = ${repos.name}`);
    console.log(`name = ${repos.caption}`);
    console.log(`ToolBar.Caption = ${repos.ToolBar.Caption}`);
    console.log(`ToolBar.name= ${repos.ToolBar.name}`);
});













url = `https://cdn.xgqfrms.xyz/json/user1.json`;

fetch(url)
.then((response) => response.json())
.then((json)=> {
    console.log(`json = ${json}`);
    return repos = json;
})
.then((repos)=>{
    console.log(`firstName = ${repos.firstName}`);
    console.log(`age = ${repos.age}`);
    console.log(`city = ${repos.address.city}`);
    console.log(`phoneNumber = ${repos.phoneNumber[0].number}`);
    console.log(`repos.length = ${repos.length}`);
});





const data = [
    {"id": "1", "name": "name_1", "parent_id": "0", "depth": "0"},
    {"id": "2", "name": "name_2", "parent_id": "0", "depth": "0"},
    {"id": "3", "name": "name_3", "parent_id": "1", "depth": "1"},
    {"id": "4", "name": "name_4", "parent_id": "3", "depth": "2"}
];

let object = data[0];

for (let key in object) {
    if (object.hasOwnProperty(key)) {
        console.log(`key = ${key}`);
        let key1 = object.key;
        let key2 = object[key];
        console.log(`object.${key} = ${key1}`);
        console.log(`object[${key}] = ${key2}`);
    }
}


url = `https://cdn.xgqfrms.xyz/json/datalist.json`;

fetch(url)
.then((response) => response.json())
.then((json)=> {
    console.log(`json = ${json}`);
    let obj_length = Object.keys(json).length;
    console.log(`json length = ${obj_length}`);
    return repos = json;
})
.then((repos)=>{
    console.log(`repos.length = ${Object.keys(repos).length}`);
    array.forEach(function(element) {
        // 
    }, this);
    for (let key in object) {
        if (object.hasOwnProperty(key)) {
            console.log(`key = ${key}`);
            let key1 = object.key;
            let key2 = object[key];
            console.log(`object.${key} = ${key1}`);
            console.log(`object[${key}] = ${key2}`);
        }
    }
    for (let key in object) {
        if (object.hasOwnProperty(key)) {
            // 
            let element = object[key];
            console.log(`object.${key} = ${element}`);
        }
    }
    for (var index = 0; index < array.length; index++) {
        var element = array[index];
        
    }
    console.log(`id = ${repos[0].id}`);
    console.log(`name = ${repos[0].name}`);
    console.log(`isParent = ${repos[0].isParent}`);
});




let obj = {a: 1, b: 2, c: 3};

for (var prop in obj) {
    console.log(`obj.${prop} = ${obj[prop]}`);
}


/*

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of



The for...of statement creates a loop iterating over iterable objects 
(including Array, Map, Set, String, TypedArray, arguments object and so on), 
invoking a custom iteration hook with statements to be executed for the value of each distinct property.


for...of 语句在可迭代对象
(包括 Array, Map, Set, String, TypedArray,arguments 对象等等)上创建一个迭代循环
,对每个不同属性的属性值,调用一个自定义的有执行语句的迭代挂钩.


let iterable = [10, 20, 30];

for (const value of iterable) {
    console.log(value);
}
// 10
// 20
// 30

let iterable = "boo";

for (let value of iterable) {
    console.log(value);
}
// "b"
// "o"
// "o"

let iterable = new Uint8Array([0x00, 0xff]);

for (let value of iterable) {
    console.log(value);
}
// 0
// 255


let articleParagraphs = document.querySelectorAll("article > p");

for (let paragraph of articleParagraphs) {
    paragraph.classList.add("read");
}

// Set 对象允许你存储任何类型的唯一值,无论是(原始值或者对象引用)。


https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Set


// Map 对象保存键值对。任何值(对象或者原始值) 都可以作为一个键或一个值。

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Map


// 一个TypedArray 对象描述一个底层的二进制数据缓存区的一个类似数组(array-like)视图。


https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/TypedArray








*/


/*

// Object.keys() 方法返回一个给定对象自己的枚举属性的数组,其顺序与 for...in 循环(区别在于,for-in 循环也枚举原型链中的属性)。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys


// for...in 语句以原始插入顺序迭代一个对象的可枚举属性。 对于每个不同的属性,可以执行语句

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

*/




// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/keys


/*

var arr = ['a', 'b', 'c'];
var iterator = arr.keys();

console.log(iterator.next()); // { value: 0, done: false }
console.log(iterator.next()); // { value: 1, done: false }
console.log(iterator.next()); // { value: 2, done: false }
console.log(iterator.next()); // { value: undefined, done: true }


*/

@xgqfrms-GitHub
Copy link

xgqfrms-GitHub commented Jun 27, 2017

@xgqfrms-GitHub
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment